python-3.x - 如何转换回调结果?
问题描述
我是 ctypes 的新手,但我想使用以下回调签名创建一个回调函数:
def autosetup_callback(p0, p1, p2):
"""This is my callback function signature
void(__stdcall *pGUIFunction)(SIndex sIndex, unsigned int statusFlag, unsigned int, const char message[512])
"""
print('autosetup arguments', p0, p1, p2)
sn= c.c_uint(0)
autosetup_cb_format = c.CFUNCTYPE(sn, c.c_uint, c.c_uint, c.c_char)
调用此回调时,我收到以下错误:
File "_ctypes/callbacks.c", line 257, in 'converting callback result'
TypeError: an integer is required (got type NoneType)
settings: values p1,p2,p3: 0 0 0
autosetup arguments 0 0 b'\x18' ### This is what the callback should print
Exception ignored in: <function autosetup_callback at 0x000001E3D4135A60>
有任何想法吗?
解决方案
您的示例中存在一些不一致之处:
- 你的函数原型有四个参数,但你的 Python 实现中只有三个参数。
__stdcall
应该使用WINFUNCTYPE
notCFUNCTYPE
。sn
是一个实例,而不是一个类型。回调定义的第一个参数是返回值( Pythonvoid
中的 ,None
)。- 最后一个参数类型是
char[512]
(decays tochar*
soc_char_p
是回调定义中需要的。
这是一个工作示例。鉴于:
测试.c
#define API __declspec(dllexport) // Windows-specific export
typedef int SIndex;
typedef void(__stdcall *CALLBACK)(SIndex sIndex, unsigned int statusFlag, unsigned int, const char message[512]);
CALLBACK g_callback;
API void set_callback(CALLBACK pFunc)
{
g_callback = pFunc;
}
API void call()
{
g_callback(1,2,3,"Hello");
}
测试.py
from ctypes import *
CALLBACK = WINFUNCTYPE(None,c_int,c_uint,c_uint,c_char_p)
@CALLBACK
def autosetup_callback(p0, p1, p2, p3):
print('autosetup arguments', p0, p1, p2, p3)
dll = CDLL('test')
dll.set_callback.argtypes = CALLBACK,
dll.set_callback.restype = None
dll.call.argtypes = None
dll.call.restype = None
dll.set_callback(autosetup_callback)
dll.call()
输出:
autosetup arguments 1 2 3 b'Hello'
推荐阅读
- influxdb - InfluxDB 中有多少标签是最优的
- compiler-construction - 我的指令如何知道操作数堆栈上的地址指向什么?
- multithreading - 如何将多个线程函数结果存储到一个数组或向量中
- javascript - 大于运算符不使用 if 语句
- kubernetes - Ghost Drillbit(集群中的一个或多个钻头具有不同的版本:未定义。)
- python - 如何从numpy中的D数组制作一个D维坐标数组
- javascript - 如何将幻灯片从左侧窗帘菜单转换为从右侧滑入
- javascript - 如何在日期对象之间创建范围
- php - Blade 指令不起作用,代码一直显示在浏览器中而不是执行
- python - 如何使用值计数出现并将它们乘以整数来产生值?