ctypes:passing python class instances through c and back

M

m2i3k

Hi
I have C code with requires me to register a python callback. I am
able to get the callback working well using ctypes if I use global
functions without any context argument for the callback.

Now I want to register a python class member function for callback,
and give "self" as the context argument at the time of callback
registration. Then the c code can invoke the callback with self as the
context argument

class SomeClass(object):
def __init__(self):
self.msg = 'Hello'

def callbackMethod(context):
# self = somemagic(context) <<<<<< how to convert this ptr
back to instance???
print self.msg

CALLBACK_FN_TYPE = WINFUNCTYPE(None,c_void_p)

s=SomeClass()
registerCallback(CALLBACK_FN_TYPE(s.callbackMethod),py_object(self))

If I print context that comes in the callback, it is the address of
the instance 's'. Now how do I generate the class instance back from
the void* context that is passed into the callback?
 
G

Gabriel Genellina

I have C code with requires me to register a python callback. I am
able to get the callback working well using ctypes if I use global
functions without any context argument for the callback.

Now I want to register a python class member function for callback,
and give "self" as the context argument at the time of callback
registration. Then the c code can invoke the callback with self as the
context argument

Use a bound method as the callback -that is, get the method from an
instance, not from the class-.
Pass it the same way as you would pass a global function; you get the
"self" argument for free :)
 

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,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top