ctypes:passing python class instances through c and back

m2i3k m2i3k2000 at gmail.com
Thu Jul 26 17:18:04 CEST 2007


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?




More information about the Python-list mailing list