简体   繁体   English

Python ctypes,将c_void_p作为out函数传递给c函数

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

I'm writing a Python module that wraps some C++ code. 我正在编写一个包装一些C ++代码的Python模块。 I used to use this function to pass a pointer from C++ to Python (the pointer would be freed by a different function 我曾经使用这个函数将指针从C ++传递给Python(指针将由不同的函数释放

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)

But now I can't seem to get the value of the pointer, in Python I set up the function with ctypes as follows 但是现在我似乎无法获得指针的值,在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   

Then I use the function by creating a new void pointer in Python and passing it to the dll function 然后我通过在Python中创建一个新的void指针并将其传递给dll函数来使用该函数

p = c_void_p()

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

print p

After running this code I am left with p equal to c_void_p(None) . 运行此代码后,我的p等于c_void_p(None)

Passing this pointer to other functions causes illegal access exceptions at address 0x0, so I don't think it is being updated. 将此指针传递给其他函数会导致地址0x0处的非法访问异常,因此我认为它不会被更新。

I am expected some address to populate p after execution. 我期望一些地址在执行后填充p I am missing something with ctypes? 我错过了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? 我可以通过分配(c_double * 10)()并将其传递给要写入的c函数来创建一个double数组,为什么我不能为同一目的传递一个void指针?

As eryksun's comment points out, for void* to be an output parameter, it should be 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM