Python ctypes,将c_void_p作为out参数传递给c函数 [英] Python ctypes, pass c_void_p as an out parameter to c function
问题描述
我正在编写一个包装一些C ++代码的Python模块。我曾经使用此函数将指针从C ++传递到Python(该指针将由其他函数释放
I'm writing a Python module that wraps some C++ code. I used to use this function to pass a pointer from C++ to Python (the pointer would be freed by a different function
DLLEXPORT void* run(double input1, double input2)
我添加了错误返回代码,所以我的新函数看起来像
I've added error return codes so my new function looks like
DLLEXPORT int run(double input1, double input2, void* output)
但是现在我似乎无法获得指针的值,在Python中按如下所示使用ctypes设置函数
But now I can't seem to get the value of the pointer, in Python I set up the function with ctypes as follows
from ctypes import *
mydll = cdll.mydll
mydll.run.argtypes = [c_double, # input 1
c_double, # input 2
c_void_p] # output pointer
mydll.run.restype = c_int
然后我通过在Python和passin中创建一个新的void指针来使用该函数将其添加到dll函数
Then I use the function by creating a new void pointer in Python and passing it to the dll function
p = c_void_p()
retval = mydll.run(1.2, 3.4, p)
print p
运行这段代码后,剩下的 p
等于 c_void_p(None)
。
After running this code I am left with p
equal to c_void_p(None)
.
将此指针传递给其他函数会导致地址0x0处的非法访问异常,因此我认为它没有被更新。
Passing this pointer to other functions causes illegal access exceptions at address 0x0, so I don't think it is being updated.
我是预计执行后会在 p
中填充一些地址。我缺少ctypes吗?我可以通过分配(c_double * 10)()
来创建一个双精度数组,并将其传递给要写入的c函数,为什么不能为
I am expected some address to populate p
after execution. I am missing something with ctypes? I can create a double array by allocating (c_double * 10)()
and pass that to c function to be written to, why can't I pass a void pointer for the same purpose?
推荐答案
正如eryksun的评论所指出的, void *
要作为输出参数,应为 void ** :
As eryksun's comment points out, for void*
to be an output parameter, it should be void**
:
# DLLEXPORT int run(double input1, double input2, void** output)
from ctypes import *
mydll = cdll.mydll
mydll.run.argtypes = [c_double, # input 1
c_double, # input 2
POINTER(c_void_p)] # output pointer
mydll.run.restype = c_int
p = c_void_p()
retval = mydll.run(1.2,3.4,byref(p))
print p.contents
这篇关于Python ctypes,将c_void_p作为out参数传递给c函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!