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

J

James Whetstone

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
 
J

James Whetstone

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



}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top