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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With