How can I get methods to work as callbacks with python ctypes?

前端 未结 3 1670
遥遥无期
遥遥无期 2020-12-17 16:42

I have an C api that i\'m interfacing with the python ctypes package. Everything works well, except this little tidbit.

To register functions as callbacks to some n

3条回答
  •  太阳男子
    2020-12-17 17:26

    Its been said but the segfault is probably caused by the garbage collection of the method, you have to store the reference. I solved both the missing self parameters and the garbage collection problem like this.

    CALLBACK = ctypes.CFUNCTYPE(None, ctypes.POINTER(Notification))
    
    class MyClass(object):
        def myPythonCallback(self, Notification):
            ...do something with Notification
        
        def __init__(self):        
            self.myPythonCallback = CALLBACK(self.myPythonCallback)
            myLib.RegisterNofityCallback(45454, 0, self.myPythonCallback)
    

    Every new instance of the class create the bound method (self.myPythonCallback), so each registered callback is specific to the class instance. We've held the reference to the callback in the class so it wont get garbage collected. The CFUNCTIONTYPE callback is executed as per normal same as if it were a global function , and its inner callback is the bound method . Bound methods execute with self.

    Note: although it looks a lot like you could just use @decorator syntax, that won't work. Decorators on methods decorate the original method and then bind to the class, so the effect is self.myPythonCallback would be a calling a plain method

    The closeure solution provided by @David-Heffernan was my inspiration,

提交回复
热议问题