从ctypes指针到结构数组的NumPy结构化/常规数组 [英] NumPy structured / regular array from ctypes pointer to array of structs
本文介绍了从ctypes指针到结构数组的NumPy结构化/常规数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下C
函数:
void getArrOfStructs(SomeStruct** ptr, int* numElements)
以及以下C
结构:
typedef struct SomeStruct
{
int x;
int y;
};
我能够成功获取Python列表:
I am able to successfully get a Python list:
class SomeStruct(Structure):
_fields_ = [('x', c_int),
('y', c_int)]
ptr, numElements = pointer(SomeStruct()), c_int()
myDLL.getArrOfStructs(byref(ptr), byref(numElements)))
我想获得一个NumPy结构化/常规数组.
I want to get a NumPy structured / regular array.
- 结构化数组与常规数组:从术语上讲,哪个更可取?
- 我该怎么办?我正在寻找一种有效的方法(不复制每个单元格).我尝试了NumPy的
frombuffer()
函数,但只能与常规的C
数组一起使用.
- Structured vs Regular array: which one is preferable (in terms of terminology)?
- How can I do it? I'm looking for an efficient way (without copy each cell). I tried NumPy's
frombuffer()
functions, but was only able to use it with regularC
arrays.
推荐答案
numpy数组的视图共享一个数据缓冲区
Views of numpy arrays share a data buffer
In [267]: x=np.arange(6).reshape(3,2)
In [268]: x.tostring()
Out[268]: b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00'
In [269]: x.view('i,i')
Out[269]:
array([[(0, 1)],
[(2, 3)],
[(4, 5)]],
dtype=[('f0', '<i4'), ('f1', '<i4')])
在此示例中,数据缓冲区是一个24字节的C数组,可以通过多种方式查看-平面数组,2列或具有2个字段的结构化数组.
In this example the databuffer is a C array of 24 bytes, which can viewed in various ways - a flat array, 2 columns, or structured array with 2 fields.
我还没有使用ctypes
,但是我确定有与np.frombuffer
等效的东西可以从字节缓冲区构造数组.
I haven't worked with ctypes
but I'm sure there's something equivalent to np.frombuffer
to construct an array from a byte buffer.
In [273]: np.frombuffer(x.tostring(),int)
Out[273]: array([0, 1, 2, 3, 4, 5])
In [274]: np.frombuffer(x.tostring(),'i,i')
Out[274]:
array([(0, 1), (2, 3), (4, 5)],
dtype=[('f0', '<i4'), ('f1', '<i4')])
这篇关于从ctypes指针到结构数组的NumPy结构化/常规数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文