NumPy structured / regular array from ctypes pointer to array of structs
<p>Say I have the following <code>C</code> function:</p>

<pre><code>void getArrOfStructs(SomeStruct** ptr, int* numElements)
</code></pre>

<p>And the following <code>C</code> struct:</p>

<pre><code>typedef struct SomeStruct
{
    int x;
    int y;
};
</code></pre>

<p>I am able to successfully get a Python list:</p>

<pre><code>class SomeStruct(Structure):
    _fields_ = [('x', c_int),
                ('y', c_int)]
ptr, numElements = pointer(SomeStruct()), c_int()
myDLL.getArrOfStructs(byref(ptr), byref(numElements)))
</code></pre>

<p>I want to get a NumPy structured / regular array.  </p>

<ol>
<li>Structured vs Regular array: which one is preferable (in terms of terminology)?</li>
<li>How can I do it? I'm looking for an efficient way (without copy each cell). I tried NumPy's <code>frombuffer()</code> functions, but was only able to use it with regular <code>C</code> arrays.</li>
</ol>

<p>Views of numpy arrays share a data buffer</p>

<pre><code>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', '&lt;i4'), ('f1', '&lt;i4')])
</code></pre>

<p>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.</p>

<p>I haven't worked with <code>ctypes</code> but I'm sure there's something equivalent to <code>np.frombuffer</code> to construct an array from a byte buffer.</p>

<pre><code>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', '&lt;i4'), ('f1', '&lt;i4')])
</code></pre>

python numpy ctypes