Python ctypes,将 c_void_p 作为输出参数传递给 c 函数

Python ctypes, pass c_void_p as an out parameter to c function

我正在编写一个包含一些 C++ 代码的 Python 模块。我曾经使用此函数将指针从 C++ 传递到 Python(指针将由不同的函数释放

DLLEXPORT void* run(double input1, double input2)

我添加了错误 return 代码,所以我的新函数看起来像

DLLEXPORT int run(double input1, double input2, void* output)

但现在我似乎无法获取指针的值,在Python我用ctypes设置函数如下

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 中创建一个新的 void 指针并将其传递给 dll 函数来使用该函数

p = c_void_p()

retval = mydll.run(1.2, 3.4, p)

print p

在 运行 之后,我得到 p 等于 c_void_p(None)

将此指针传递给其他函数会导致地址0x0出现非法访问异常,所以我认为它没有被更新。

我希望在执行后填充一些地址 p。我缺少 ctypes 的东西吗?我可以通过分配 (c_double * 10)() 来创建一个双精度数组并将其传递给要写入的 c 函数,为什么我不能为相同的目的传递一个 void 指针?

正如 eryksun 的评论所指出的,对于 void* 作为输出参数,它应该是 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