Python ctypes,将c

编程入门 行业动态 更新时间:2024-10-22 20:37:25
本文介绍了Python ctypes,将c_void_p作为out参数传递给c函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个包装一些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

本文发布于:2023-07-29 08:56:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   ctypes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!