带ctypes的回调(如何从C调用python函数) [英] Callbacks with ctypes (How to call a python function from C)

查看:148
本文介绍了带ctypes的回调(如何从C调用python函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我们考虑使用此C函数:

We consider this C function:

 void foo( void (*functionPtr)(int,int) , int a, int b);

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

On Python, I would like to call foo and set the callback to a Python function:

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 文档对这个主题很轻并且上面的代码不起作用。

Unfortunately, the ctypes documentation is pretty light on this topic and the above code does not work.

推荐答案

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

如果需要 stdcall 调用约定,请改用 WINFUNCTYPE

If you need stdcall calling conventions, use WINFUNCTYPE instead.

注意:如果 foo 可能会存储要在以后调用的回调,然后确保Python回调处于活动状态(如果使用装饰器在全局级别定义了Python回调就足够了。在示例中-除非您尝试显式删除模块,否则模块在Python中实际上是不朽的。

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).

这篇关于带ctypes的回调(如何从C调用python函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆