gpt4 book ai didi

python - 使用 ctypes 访问变量数组的内容

转载 作者:太空狗 更新时间:2023-10-30 01:24:17 25 4
gpt4 key购买 nike

我使用 ctypes 访问文件读取 python 中的 C 函数。由于读取数据巨大且大小未知,因此我在 C 中使用 **float

int read_file(const char *file,int *n_,int *m_,float **data_) {...}

函数 mallocs 一个二维数组,称为 data,具有适当的大小,这里是 nm , 并将值复制到引用的值。请参阅以下代码段:

*data_ = data;
*n_ = n;
*m_ = m;

我使用以下 python 代码访问此函数:

p_data=POINTER(c_float)
n=c_int(0)
m=c_int(0)
filename='datasets/usps'
read_file(filename,byref(n),byref(m),byref(p_data))

之后,我尝试使用 contents 访问 p_data,但我只得到一个浮点值。

p_data.contents
c_float(-1.0)

我的问题是:如何在 python 中访问 data

您有什么建议?如果我有什么不清楚的地方,请不要犹豫指出!

最佳答案

使用 struct 库在 python 中完成整个事情可能会更简单。但是如果你在 ctypes 上卖了(我不怪你,这很酷):

#include <malloc.h>
void floatarr(int* n, float** f)
{
int i;
float* f2 = malloc(sizeof(float)*10);
n[0] = 10;
for (i=0;i<10;i++)
{ f2[i] = (i+1)/2.0; }
f[0] = f2;
}

然后在 python 中:

from ctypes import *

fd = cdll.LoadLibrary('float.dll')
fd.floatarr.argtypes = [POINTER(c_int),POINTER(POINTER(c_float))]

fpp = POINTER(c_float)()
ip = c_int(0)
fd.floatarr(pointer(ip),pointer(fpp))
print ip
print fpp[0]
print fpp[1]

诀窍在于大写字母 POINTER 生成类型,小写字母 pointer 生成指向现有存储的指针。你可以使用 byref 而不是 pointer,他们声称它更快。我更喜欢 pointer,因为它更清楚发生了什么。

关于python - 使用 ctypes 访问变量数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3620348/

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