List of Structure subclass returns wrong values when casting to numpy array
<p>I've built a simple Structure subclass with two fields, holding a void pointer to an array, and the array length. However, when I try to create a list of these using input lists of the same length, the value of the returned void pointer is the same as the last array used to create the instance:</p>

<pre><code>from ctypes import POINTER, c_double, c_size_t, c_void_p, Structure, cast
import numpy as np

class External(Structure):

    _fields_ = [("data", c_void_p),
                ("length", c_size_t)]
    @classmethod
    def from_param(cls, seq):
        return seq if isinstance(seq, cls) else cls(seq)

    def __init__(self, seq):
        self.ptr = cast(
            np.array(seq, dtype=np.float64).ctypes.data_as(POINTER(c_double)),
            c_void_p
        )
        self.data = self.ptr
        self.length = len(seq)
        # recreate array from void pointer
        # shows the correct values
        shape = self.length, 2
        ptr = cast(self.data, POINTER(c_double))
        array = np.ctypeslib.as_array(ptr, shape)
        print "Correct array", array.tolist()

if __name__ == "__main__":
    interiors = [
            [[3.5, 3.5], [4.4, 2.0], [2.6, 2.0], [3.5, 3.5]],
            [[4.0, 3.0], [4.0, 3.2], [4.5, 3.2], [4.0, 3.0]],
            ]
    wrong = [External(s) for s in interiors]
    for w in wrong:
        # perform same cast back to array as before
        shape = w.length, 2
        ptr = cast(w.data, POINTER(c_double))
        array = np.ctypeslib.as_array(ptr, shape)
        print "Wrong array", array.tolist()
</code></pre>

<p>If I create my <code>External</code> instances using input lists of difference lengths, everything works as expected. What am I doing wrong here?</p>

<p>The problem is that the numpy array is immediately garbage-collected and the underlying memory freed, resulting in a dangling pointer.</p>

<p>The solution is to keep a reference to the underlying <code>buffer</code> object:</p>

<pre><code>def __init__(self, seq):
    array = np.array(seq, dtype=np.float64)
    self._buffer = array.data
    self.ptr = cast(
        array.ctypes.data_as(POINTER(c_double)),
        c_void_p
    )
    ...
</code></pre>

<p>Now the memory for the array is freed only when the instance of <code>External</code> holding the reference gets deleted.</p>

python arrays numpy ctypes