使用 ctypes 访问变量数组的内容
我使用 ctypes 来访问读取 python 中 C 函数的文件。由于读取的数据巨大且大小未知,我在 C 中使用 **float
。
int read_file(const char *file,int *n_,int *m_,float **data_) {...}
函数 mallocs
一个二维数组,称为 data
,具有适当的大小,此处为 n
和 m
,并将值复制到引用的值。请参阅以下代码片段:
*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 中访问数据
?
你有什么建议?如果我留下不清楚的地方,请随时指出!
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_) {...}
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;
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))
Afterwards I try to acces p_data
using contents
, but I get only a single float value.
p_data.contents
c_float(-1.0)
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 struct 库在 python 中完成整个事情可能会更简单。但如果你对 ctypes 感兴趣(我不怪你,这很酷):
然后在 python 中:
诀窍是大写
POINTER
生成类型,小写pointer< /code> 创建一个指向现有存储的指针。你可以使用
byref
代替pointer
,他们声称这样更快。我更喜欢pointer
因为它更清楚发生了什么。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):and then in python:
the trick is that capitals
POINTER
makes a type and lowercasepointer
makes a pointer to existing storage. you can usebyref
instead ofpointer
, they claim it's faster. I likepointer
better because it's clearer what's happening.