gpt4 book ai didi

python - C类型, python 。如何在函数参数之一中传回指向 C 动态分配的 double 组的指针?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:44 25 4
gpt4 key购买 nike

我有一个 C 函数 void get_data(int &len, double* data),它为数据动态分配内存(大小事先未知)并返回指向数据的指针。我想使用 ctypes 从 python 调用它。

带有 double* data = get_data(int &len) 的版本工作正常,但我需要通过参数传递指针的版本,因为我有多个数据 vector 。

我尝试了很多不同的方法,但没有任何效果:

fun = cfun.get_data
fun.argtypes = [ct.c_int, ct.POINTER(ct.c_int)]
fun.restype = None

len = ct.c_int()
data_ptr = ct.POINTER(ct.c_double)()

fun(len, data_ptr)

bool(data_ptr) -- NULL -- 它不是可变的,所以保持为 NULL在 C 函数为其分配新值之后。我尝试了 ct.byref(data_ptr),等等。但一直无法得到数据出。

非常感谢!

最佳答案

void get_data(int &len, double* data) which dynamically allocates the memory for data (size is not known in advance).

即使在 C 中也行不通。您将指针的 value 传递给函数。更改此值在外部是不可见的。你应该有 double** data ,例如,如果你想在 get_data 内部分配并在外部传递指针,则指向 double 的指针。

void get_data(int *len, double** data)
{
*len=12;
*data=malloc(*len);

//fill data
for(i=0;i<*len;++i) (*data)[i]=<something>;

return;
}

这是你的答案: Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL?

关于python - C类型, python 。如何在函数参数之一中传回指向 C 动态分配的 double 组的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com