C 函数myfunc
对更大的数据块进行操作。结果以块的形式返回给回调函数:
int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata);
使用ctypesmyfunc
,从 Python 代码调用并将结果返回给 Python 回调函数并不是什么大问题。这个回调工作正常。
myfunc = mylib.myfunc
myfunc.restype = c_int
myfuncFUNCTYPE = CFUNCTYPE(STRING, c_void_p)
myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE, c_void_p]
def mycb(result, userdata):
print result
return True
input="A large chunk of data."
myfunc(input, myfuncFUNCTYPE(mycb), 0)
但是,有没有办法将 Python 对象(比如列表)作为用户数据提供给回调函数?为了存储结果块,我想做例如:
def mycb(result, userdata):
userdata.append(result)
userdata=[]
但我不知道如何将 Python 列表转换为 c_void_p,以便可以在调用 myfunc 时使用它。
我目前的解决方法是将链表实现为 ctypes 结构,这很麻烦。