Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ctypes的回调(如何从C调用python函数)_Python_Ctypes - Fatal编程技术网

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

使用ctypes的回调(如何从C调用python函数),python,ctypes,Python,Ctypes,是否可以从Cdll函数调用Python函数 我们考虑这个C函数: void foo( void (*functionPtr)(int,int) , int a, int b); 在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)

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

我们考虑这个C函数:

 void foo( void (*functionPtr)(int,int) , int a, int b);
在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) )

不幸的是,
ctypes
文档对此主题的描述非常简单,上面的代码不起作用

使用
CFUNCTYPE
创建回调类型:

c_callback = CFUNCTYPE(None, c_int, c_int)(callback)
dll.foo(c_callback, a, b)
如果需要调用约定,
stdcall


注意:如果
foo
可能会存储回调以在以后调用,那么请确保Python回调是活动的(如果它是在全局级别使用decorator定义的,这就足够了,如示例所示——模块在Python中基本上是不朽的,除非您尝试显式删除它们)。

OP是显式的,Ctypes回调文档:不幸的是,该教程通常是Ctypes的实际参考。Mark给了您教程链接,但肯定在中有足够的文档记录,以超越您尝试的内容:“这些工厂函数创建的函数原型可以以不同的方式实例化,具体取决于调用中参数的类型和数量……原型(可调用),创建一个C可调用函数(回调函数)来自一个Python可调用的。
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