我是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>
有什么想法吗?
答案 0 :(得分:2)
您的示例中存在一些不一致之处:
__stdcall
应该使用WINFUNCTYPE
而不是CFUNCTYPE
。sn
是实例,而不是类型。回调定义的第一个参数是返回值(Python中的void
,None
)。char[512]
(衰减为char*
,因此回调定义中需要c_char_p
。这是一个可行的例子。鉴于:
test.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");
}
test.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'