0

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 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)))

I want to get a NumPy structured / regular array.

  1. Structured vs Regular array: which one is preferable (in terms of terminology)?
  2. 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 regular C arrays.

1 Answer 1

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')])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, chaging the dtype did the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.