[C++-sig] Boost Python and ctypes

Tristam MacDonald swiftcoder at gmail.com
Sun Feb 24 13:41:15 CET 2008

I am trying to bridge two libraries, one a C library bound into python 
using ctypes, and the other a C++ library using Boost Python.

In the C++ library, I have a class similar to the following, with a 
member function that returns a pointer to an internal buffer.

struct Test
float data[16];

float *get_data() {return data;}

I have wrapped this in a seeming logical way:

.def("get_data", &Test::get_data, return_value_policy< return_by_value >();

Which suffices to retrieve a "float *" instance from Python. However, I 
need to pass this pointer to a ctypes-bound function:

void some_function(float *);

I can call this function from python without any trouble, using a 
ctypes created buffer:

buffer = (c_float * 16)

However, when I attempt to pass the result of get_data() into this 
function, ctypes causes an error because Boost Python's "float *" type 
does not match ctypes' POINTER(c_float) type. Equally, ctypes' cast() 
function doesn't work to coerce the pointer type, because it doesn't 
recognise the "float *" type either.

Does anyone have a workaround to coerce these types (which each contain 
the same underlying pointer) together?

Thanks in advance for any suggestions,

- Tristam

More information about the Cplusplus-sig mailing list