使用ctypes访问变量数组的内容 [英] Accessing the content of a variable array with ctypes
问题描述
我使用ctypes访问python中读取C函数的文件.由于读取的数据巨大且大小未知,因此我在C中使用**float
.
I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float
in C .
int read_file(const char *file,int *n_,int *m_,float **data_) {...}
函数mallocs
具有适当大小(这里为n
和m
)的2d数组(称为data
),并将值复制到引用的值中.请参见以下代码段:
The functions mallocs
an 2d array, called data
, of the appropriate size, here n
and m
, and copies the values to the referenced ones. See following snippet:
*data_ = data;
*n_ = n;
*m_ = m;
我使用以下python代码访问此功能:
I access this function with the following python code:
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
,但是我只得到一个浮点值.
Afterwards I try to acces p_data
using contents
, but I get only a single float value.
p_data.contents
c_float(-1.0)
我的问题是:如何在python中访问data
?
My question is: How can I access data
in python?
您推荐什么?如果我有不清楚的地方,请不要犹豫指出!
What do you recommended? Please don't hesitate to point out if I left something unclear!
推荐答案
使用struct
库在python中完成整个操作可能会更简单.但是如果您以ctypes出售(我不怪你,那很酷):
might be simpler to do the whole thing in python with the struct
library. but if you're sold on ctypes (and I don't blame you, it's pretty cool):
#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
,因为这样可以更清楚地了解发生了什么.
the trick is that capitals POINTER
makes a type and lowercase pointer
makes a pointer to existing storage. you can use byref
instead of pointer
, they claim it's faster. I like pointer
better because it's clearer what's happening.
这篇关于使用ctypes访问变量数组的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!