Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes python std::string

Tags:

c++

python

ctypes

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)
like image 348
kosta5 Avatar asked Mar 14 '12 13:03

kosta5


People also ask

Is Ctypes included in Python?

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.

What is using std :: string?

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.

How do I use Ctypes pointer?

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.


2 Answers

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.

like image 130
daramarak Avatar answered Oct 04 '22 21:10

daramarak


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 ).

like image 41
James Kanze Avatar answered Oct 04 '22 20:10

James Kanze