Skip to content
Advertisement

Calling C++ function which accepts and returns std::string from Python

I’m trying to call C++ function using ctypes. The function declaration looks like

JavaScript

As Python can not interact with C++ directly, I have created a C-wrapper for this function as follows

JavaScript

And Python wrapper

JavaScript

But when I try to call Python wrapper with some bytes passed as param, for example

JavaScript

It fails with the following error

JavaScript

I’m not very good in C and C++. Can you help me to figure out how to create correct wrapper? Thanks.

Advertisement

Answer

Since your data contains embedded nulls, c_char_p won’t work as it assumes the returned char* is null-terminated and converts the data up to the first null found to a bytes object. std::string as used also makes that assumption when pass a char* only, so it needs the data length as well.

To manage a data buffer with null content, the size of the input data must be passed in and the size of the output data must be returned. You’ll also have to manage freeing the data allocated in the C++ code.

The below code demonstrates everything:

test.cpp – compiled with cl /EHsc /W4 /LD test.cpp with Microsoft Visual Studio.

JavaScript

test.py

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement