How to use boost.python to wrap a class with a pure virtual function that has a 'void *' argument

James Whetstone jameswhetstone at comcast.net
Sat Mar 22 19:42:17 EDT 2008


I found a solution to this problem:


void handleMessage(void *message)

{

int size = getSize(message);

PyObject *obj = PyBuffer_FromMemory( message, size ) ;


boost::python::handle<> h(obj);


PyGILState_STATE gstate = PyGILState_Ensure();

try

{

call<void>(this->get_override("handleMessage").ptr(), h);

}

catch (const error_already_set)

{

// Catch and ignore exception that is thrown if Python

// onMessage raised an exception. Print it to sys.stderr,

// since there is nothing we can do about it here.

PyErr_Print();

}

PyGILState_Release(gstate);



}



"James Whetstone" <jameswhetstone at comcast.net> wrote in message 
news:ubudndoRENZA-3janZ2dnUVZ_u-unZ2d at comcast.com...
> As the subject implies, I'm having trouble wrapping a C++ class that looks 
> like this:
>
> struct A
> {
>    virtual void handleMessage(void *message)=0;
> };
>
>
> To wrap this class, I've written the following code:
>
> struct AWrapper : A, wrapper<A>
> {
>    void handleMessage(void *message)
>    {
>        this->get_override("handleMessage")(message);
>    }
> };
>
> class_<AWrapper, boost::noncopyable>("A")
>    .def("handleMessage", pure_virtual(&A::handleMessage))
> ;
>
>
> My python test code looks like this:
>
> import APackage
>
> class aclass(APackage.A):
> def handleMessage(msg) : print msg
>
>
> But this code crashes when the handleMessage function is called in python 
> (I think) because 'void *' cannot be marshalled.  Is there some way around 
> this?  Also, since the void* object is intended to be "zero copy", I 
> should probably convert the void * to a PyObject first and re-write my 
> handleMessage to look like this:
>
>    void handleMessage(void *message)
>    {
>        int size = getMessageSize(message);
>
>        PyObject *obj = PyBuffer_FromReadWriteMemory(message, size);
>
>        this->get_override("handleMessage")(obj);
>    }
>
> Has anyone done this type of thing?  I'm writing this code using MS Visual 
> Studio 8 and if anyone can help, it would *very* appreciated.
>
> Thanks!
> James
>
>
>
> 





More information about the Python-list mailing list