5
votes

I am working with ctypes using C++ as the backend. Now there is a function like this in C++:

void HandleString(std::string something){

   ...
}

I am wondering how to call this function from python - there is no ctype (c_char_p wont work obviously) to send a string parameter to this function...

How can I fix this and pass a string from Python to c++ (and changing the parameter to char* something is not and option)

PS Could I create a workaround like this?

  1. send the python string as c_char_p to C++ function that converts char* to std::string
  2. return the string or its pointer somehow???!! (how?) to python
  3. send it from python to HandleString function (but again I feel like I would have to change the parameter to string* here)
2
If you're going to workaround, wouldn't it make more sense to send your c_char_p to a C++ function that converts it to std::string and then calls HandleString immediately? In fact, there's an implicit conversion from const char* to std::string, so your workaround function can just use the pointer as the argument expression for HandleString. Don't bother trying to pass the std::string back to Python. - Steve Jessop

2 Answers

4
votes

Sounds like the simplest approach is to write a thin c++ wrapper around the library for the sole purpose of renegotiating the parameters from python into the more complex c++ classes.

Such an approach would also help remedy future problems of the same kind, without adding any real complexity to neither the python code or the c++ code.

3
votes

The Python C API converts Python str objects into char*, and there is an implicit conversion in C++ from char* (actually char const*) to std::string.

If the Python strings can contain null characters, you'll have to use PyString_AsStringAndSize to convert, and pass around the two values (the char* and the Py_ssize_t); there's an explicit conversion of these to std::string as well: std::string( pointer, length ).