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

前端 未结 3 1671
遥遥无期
遥遥无期 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

    You can't, so far as I know, call a bound method because it is missing the self parameter. I solve this problem using a closure, like this:

    CALLBACK = ctypes.CFUNCTYPE(None, ctypes.POINTER(Notification))
    
    class MyClass(object):
    
        def getCallbackFunc(self):
            def func(Notification):
                self.doSomething(Notification)
            return CALLBACK(func)
    
        def doRegister(self):
            myLib.RegisterNofityCallback(45454, 0, self.getCallbackFunc())
    

提交回复
热议问题