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?
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
Creating Pointers with ctypes POINTER() takes as parameter the type of pointer you wish to create, an integer pointer for example. ctypes. pointer() takes as parameter an object, which it then returns a pointer to. The pointer() however, only accepts datatypes from the ctypes module.
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.
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 )
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With