[SciPy-user] numpy array in ctype struct
Travis E. Oliphant
oliphant@enthought....
Tue Jan 15 08:59:06 CST 2008
Paul Kienzle wrote:
> Hi,
>
> We are trying to create the following struct in ctypes:
>
> struct {
> int n,k;
> double A[4][4], B[4][4];
> } ;
>
> Easy enough:
>
> class embedded_array(Structure):
> _fields_ = [("n",c_int),("k",c_int),("A",c_double*16),("B",c_double*16)]
> instance = embedded_array()
>
> Question:
>
> Is there a way to map the data in A/B into a numpy array, so that we
> can use it directly?
>
>
Yes. You can create an array from a pointer to memory and a
description of the data that is much like the ctypes structure. At
some point, there should be a direct conversion from ctypes objects to
NumPy data-types, but nobody has written that yet. At the moment you
have to create a dtype object that is parallel to the ctypes one:
import numpy as np
dt = np.dtype([('n',np.intc),('k',np.intc),("A", float, 16), ("B",
float, 16)])
Then,
arr = np.frombuffer(instance, dtype=dt)
will create a 1-d array of these structures mapping onto the data
pointed to by instance. Of course, in this case, the 1-d array only
has one element.
Access to the fields of the c-structure is obtained by "dictionary" access:
arr['n'] = 10
arr["A"] = 1
You will notice that this accesses the memory directly:
print instance.n
print [x for x in instance.A]
Ask if you need more help.
Best regards,
-Travis O.
More information about the SciPy-user
mailing list