使用ctypes进行回调(如何从C调用python函数)

now*_*wox 6 python ctypes

是否可以从C dll函数调用Python 函数?

我们考虑这个C函数:

 void foo( void (*functionPtr)(int,int) , int a, int b);
Run Code Online (Sandbox Code Playgroud)

在Python上,我想调用foo并将回调设置为Python函数:

def callback(a, b):
    print("foo has finished its job (%d, %d)" % (a.value,b.value))

dll.foo( callback, c_int(a), c_int(b) )
Run Code Online (Sandbox Code Playgroud)

不幸的是,ctypes文档对这个主题非常清楚,上面的代码不起作用.

jfs*_*jfs 10

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
Run Code Online (Sandbox Code Playgroud)

如果你需要stdcall调用约定,使用WINFUNCTYPE代替.

注意:如果foo可以存储稍后要调用的回调,那么确保Python回调是活的(如果它是使用装饰器在全局级别定义的就足够了,如示例所示 - 模块在Python中基本上是不朽的除非你试图明确删除它们.