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

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

    This may be a ctypes bug dealing with the magic behind setting up the stack for methods vs functions.

    Have you tried using a wrapper via lambda or function?

    Lambda:

    func = CALLBACK(lambda x: myPythonCallback(x))
    

    Function:

    def wrapper(x): myPythonCallback(x)
    func = CALLBACK(wrapper)
    

    There's a third method using closures. If you're setting up the callback from inside the class, the method defined below should inherit the "self" argument due to scope - making it act like a class method despite being a regular function.

    class Foo:
        def __init__(self):
            def myPythonCallback(Notification):
                print self # it's there!
                pass # do something with notification
    
            func = CALLBACK(myPythonCallback)
            myLib.RegisterNofityCallback(45454, 0, func)
    

提交回复
热议问题