[Numpy-discussion] frombuffer alignment for ctypes.Structure array

David Cournapeau david@ar.media.kyoto-u.ac...
Fri Apr 10 03:28:23 CDT 2009


Roland Schulz wrote:
> The is no align or aligned option to frombuffer. What is the best way
> to tell numpy to align the data as the C-struct/ctypes.Stucture array is?

You could add a 'fake' field in between to get the right alignment, maybe ?

import numpy as N
from ctypes import *

class C(Structure):
    _fields_=[("a",c_int),("b",c_short), ('', c_short)]

c=(C*2)()
_ctypes_to_numpy = {c_short : N.int16,c_int : N.int32}
ty = N.dtype([(x,_ctypes_to_numpy[y]) for x,y in C._fields_])
x=N.frombuffer(c,ty)

You may use a different type if you need another alignment, or using
something like 'VN' in the dtype, e.g.:

a = N.dtype([('a', np.int), ('b', np.short), ('', 'V2')])

David


More information about the Numpy-discussion mailing list