[C++-sig] Boost Python and ctypes

Joseph Lisee jlisee at gmail.com
Tue Feb 26 20:34:24 CET 2008

I don't know how to integrate this into Boost.Python in a clean way, but here 
is a litter terminal example that can help:

>>> array = (ctypes.c_int * 3)(1,2,3)
>>> addr = ctypes.addressof(array)
>>> arrayPtr = ctypes.cast(addr, ctypes.POINTER((ctypes.c_int)))
>>> array[0]
>>> arrayPtr[0]

So basically if you can get a long value into python representing the address 
of your float array you are good to go.  This is done in Python-Ogre by just 
wrapping a manual cast function:

unsigned long castToAddress(float* ptr)
    return (unsigned long)ptr;

A more permanent way to do this would be to change your wrapper to execute 
this code with Boost.Python's C++ python API interface (not tested):

bp::object convertFloat(float* ptr)
    bp::object ctypes = bp::import("ctypes");

    bp::long addr((unsigned addr)ptr);
    bp::object pointerType(ctypes["POINTER"](ctypes["c_float"]));

    return ctypes["cast"](addr, pointerType);

I believe you can do this by specifying a manual to python convert for the 
"float*" type.

Hope that helps,
Joseph Lisee

More information about the Cplusplus-sig mailing list