Ctypes python std :: string

I work with ctypes using C ++ as a backend. Now in C ++ there is such a function:

void HandleString(std::string something){ ... } 

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

How can I fix this and pass a string from Python to C ++ (and change the parameter to char * something is wrong and an option)

PS Can I create a workaround like this?

  • send the python string as c_char_p to a C ++ function that converts char * to std :: string
  • return the string or its pointer somehow ??? !! (how?) in python
  • send it using the python function in HandleString (but again it seems to me that I need to change the parameter to the string * here)
+4
source share
2 answers

It seems like the easiest approach is to write a thin C ++ shell around the library for the sole purpose of revising parameters from python to more complex C ++ classes.

Such an approach would also help eliminate future problems of the same type, without adding any real complexity to either the python code or the C ++ code.

+3
source

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

If Python strings can contain null characters, you will have to use PyString_AsStringAndSize to convert and pass two values ​​( char* and Py_ssize_t ); there is an explicit conversion, they are also std::string : std::string( pointer, length ) .

+3
source

Source: https://habr.com/ru/post/1401381/


All Articles