Python 对象作为 ctypes 回调函数中的用户数据 [英] Python objects as userdata in ctypes callback functions
问题描述
C 函数 myfunc
对更大的数据块进行操作.结果以块的形式返回给回调函数:
The C function myfunc
operates on a larger chunk of data. The results are returned in chunks to a callback function:
int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata);
使用ctypes,从Python 代码调用myfunc
并将结果返回给Python 回调函数没什么大不了的.这个回调工作正常.
Using ctypes, it's no big deal to call myfunc
from Python code, and to have the results being returned to a Python callback function. This callback work fine.
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 对象(比如列表)作为用户数据提供给回调函数?为了存储结果块,我想做例如:
But, is there any way to give a Python object (say a list) as userdata to the callback function? In order to store away the result chunks, I'd like to do e.g.:
def mycb(result, userdata):
userdata.append(result)
userdata=[]
但我不知道如何将 Python 列表转换为 c_void_p,以便它可以在对 myfunc 的调用中使用.
But I have no idea how to cast the Python list to a c_void_p, so that it can be used in the call to myfunc.
我目前的解决方法是将链表实现为ctypes结构,比较麻烦.
My current workaround is to implement a linked list as a ctypes structure, which is quite cumbersome.
推荐答案
我想你可以使用 Python C API 来做到这一点……也许你可以使用 PyObject 指针.
I guess you could use the Python C API to do that... maybe you could use a PyObject pointer.
edit:正如 op 在评论中指出的那样,ctypes 中已经有一个 py_object
类型,因此解决方案是先创建一个 ctypes.py_object
对象,然后将其转换为 c_void_p
以将其作为参数传递给 C 函数(我认为这一步可能是不必要的,因为作为参数键入为 void*
应该接受任何指针,并且只传递一个 byref
会更快).在回调中,完成了相反的步骤(从 void 指针转换为指向 py_object
的指针,然后获取内容的值).
edit: As the op pointed out in the comments, there's already a py_object
type readily available in ctypes, so the solution is to create first a ctypes.py_object
object from the python list and then casting it to c_void_p
to pass it as an argument to the C function (I think this step might be unnecessary as a parameter typed as void*
should accept any pointer, and it would be faster to pass just a byref
). In the callback, the reverse steps are done (casting from the void pointer to a pointer to py_object
and then getting the value of the contents).
一种解决方法可能是为您的回调函数使用闭包,以便它已经知道它必须将项目附加到哪个列表中...
A workaround could be to use a closure for your callback function so it already knows in which list it has to append the items...
myfunc = mylib.myfunc
myfunc.restype = c_int
myfuncFUNCTYPE = CFUNCTYPE(STRING)
myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE]
def mycb(result, userdata):
userdata.append(result)
input="A large chunk of data."
userdata = []
myfunc(input, myfuncFUNCTYPE(lambda x: mycb(x, userdata)))
这篇关于Python 对象作为 ctypes 回调函数中的用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!