Numpy Structured / Regular Array From Ctypes Pointer To Array Of Structs
Say I have the following C function: void getArrOfStructs(SomeStruct** ptr, int* numElements) And the following C struct: typedef struct SomeStruct { int x; int y; }; I a
Solution 1:
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')])
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.
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')])
Post a Comment for "Numpy Structured / Regular Array From Ctypes Pointer To Array Of Structs"