Callbacks with ctypes (How to call a python function from C)

后端 未结 2 1898
轻奢々
轻奢々 2020-12-11 02:28

Is it possible to call a Python function from a C dll function?

We consider this C function:

 void foo( void (*functionPtr)(int,int) , i         


        
2条回答
  •  半阙折子戏
    2020-12-11 02:53

    import ctypes as c
    
    @c.CFUNCTYPE(None, c.c_int, c.c_int)
    def callback(a, b):
        print("foo has finished its job (%d, %d)" % (a.value, b.value))
    
    dll.foo(callback, a, b) # assuming a,b are ints
    

    If you need stdcall calling conventions, use WINFUNCTYPE instead.

    Note: if foo may store the callback to be called at a later time then make sure that Python callback is alive (it is enough if it is defined at the global level using the decorator as shown in the example -- modules are essentially immortal in Python unless you try to remove them explicitly).

提交回复
热议问题