Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes - references from C to python objects

I'm using a C library from python using ctypes. There's a callback function with a void* argument I'm using as ctypes.py_object. The object pointer is given to the library when the callback is registered. However when it is no longer referenced from python code, it should be destroyed. I want it to survive until the callback function is called. How do I do that?

callback_t=ctypes.CFUNCTYPE(None, ctypes.py_object)
clib.register_callback.argtypes=[callback_t, ctypes.py_object]
clib.register_callback.restype=None

class Object:
    def __init__(self, val):
        self.val=val

def callback(obj):
    print(obj.val)

callback_c=callback_t(callback)

def calledByOtherCode(val):
    clib.register_callback(callback_c, Object(val))
like image 369
Hristo Venev Avatar asked Mar 27 '14 19:03

Hristo Venev


1 Answers

You could try incrementing/decrementing the refcount manually:

def calledByOtherCode(val):
    o = Object(val)
    pyo = ctypes.py_object(o)
    ctypes.pythonapi.Py_IncRef(pyo)
    clib.register_callback(o)

def callback(obj):
    print(obj.val)
    pyobj = ctypes.py_object(obj)
    ctypes.pythonapi.Py_DecRef(pyobj)
like image 141
kitti Avatar answered Sep 19 '22 17:09

kitti