[Numpy-discussion] Array data and struct alignment
Albert Strasheim
fullung at gmail.com
Sat Apr 29 17:27:15 CDT 2006
Thanks Travis, this works like a charm.
For the curious, here's a quick way to see if your system is doing the right
thing:
In [87]: descr = dtype({'names':['a', 'b'], 'formats':[byte,'f8']},align=1)
In [88]: descr
Out[88]: dtype([('a', '|i1'), ('', '|V7'), ('b', '<f8')])
In [89]: a=array([(1,0.0),(2,0.0)], dtype=descr)
In [92]: a.data[0]
Out[92]: '\x01'
In [93]: a.data[16]
Out[93]: '\x02'
In this case the bytes are showing where one would expect them if padding
was happening.
Regards,
Albert
> -----Original Message-----
> From: numpy-discussion-admin at lists.sourceforge.net [mailto:numpy-
> discussion-admin at lists.sourceforge.net] On Behalf Of Travis Oliphant
> Sent: 30 April 2006 00:10
> To: numpy-discussion
> Subject: Re: [Numpy-discussion] Array data and struct alignment
>
> Travis Oliphant wrote:
> > Albert Strasheim wrote:
> >> Hello all
> >>
> >> I'm busy wrapping a C library with NumPy. Some of the functions
> >> operate on a
> >> buffer containing structs that look like this:
> >>
> >> struct node {
> >> int index;
> >> double value;
> >> };
> >>
> >>
> >
> > In my previous discussion I was wrong. You cannot use the
> > array_descriptor format for a data-type and the align keyword at the
> > same time. You need to use a different method to specify fields.
> >
> > This, for example:
> >
> > descr = dtype({'names':['index', 'value'],
> > 'formats':[intc,'f8']},align=1)
> >
> > On my (32-bit) system it doesn't produce any difference from align=0.
> >
> > -Travis
> >
> >
>
> However notice the difference with
>
> >>> dtype({'names':['index', 'value'], 'formats':[short,'f8']},align=1)
> dtype([('index', '<i2'), ('', '|V2'), ('value', '<f8')])
>
> >>> dtype({'names':['index', 'value'], 'formats':[short,'f8']},align=0)
> dtype([('index', '<i2'), ('value', '<f8')])
>
>
> There is padding inserted in the first-case. This corresponds to how
> the compiler packs a short; double struct on my system. The default is
> align=0. You need to use the dtype() constructor to change the
> default. The auto-constructor used in dtype= keyword calls will not
> change the alignment from align=0.
>
>
> -Travis
More information about the Numpy-discussion
mailing list