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

问题描述 投票:0回答:1

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

DLLEXPORT void* run(double input1, double input2)

我添加了错误返回代码,所以我的新函数看起来像这样

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 指针?

python c++ ctypes
1个回答
6
投票

正如 eryksun 的评论指出的那样,对于

void*
作为输出参数,它应该是
void**
:

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

import ctypes as ct

mydll = ct.CDLL('mydll')
mydll.run.argtypes = [ct.c_double, # input 1
                      ct.c_double, # input 2
                      ct.POINTER(ct.c_void_p)] # output pointer
mydll.run.restype  = ct.c_int

p = ct.c_void_p()
retval = mydll.run(1.2, 3.4, byref(p))
print(p.contents)
© www.soinside.com 2019 - 2024. All rights reserved.