[Numpy-discussion] Create a numpy array from an array of a Cstructure

mani sabri mani.sabri@gmail....
Sun Mar 9 04:24:35 CDT 2008


I don't want to disturb the list with this kind of crap but I can't hold my
self to tell how much I love you guys!

>-----Original Message-----
>From: numpy-discussion-bounces@scipy.org [mailto:numpy-discussion-
>bounces@scipy.org] On Behalf Of Robert Kern
>Sent: Sunday, March 09, 2008 12:45 PM
>To: Discussion of Numerical Python
>Subject: Re: [Numpy-discussion] Create a numpy array from an array of a
>Cstructure
>
>On Sun, Mar 9, 2008 at 2:57 AM, mani sabri <mani.sabri@gmail.com> wrote:
>> Hello
>>
>>  Is it possible to create a numpy array from an array of a C structure
>like
>>  this?
>>
>>  struct RateInfo
>>   {
>>    unsigned int      ctm;
>>    double            open;
>>    double            low;
>>    double            high;
>>    double            close;
>>    double            vol;
>>   };
>
>Sure. On the numpy side, you would make an record array with the
>appropriate dtype and size.
>
>In [1]: from numpy import *
>
>In [2]: dt = dtype([('ctm', uint), ('open', double), ('low', double),
>('high', double), ('close', double), ('vol', double)])
>
>In [3]: a = empty(10, dtype=dt)
>
>
>On the C side, you would iterate through your C array and your numpy
>array and just assign elements from the one to the other. If you have
>a contiguous C array, you could also just use memcpy().
>
>This is probably reliable because all of your struct members take up
>multiples of 4 bytes and most C compilers will pack those without any
>space between them. If you were mixing, say, chars and doubles, the C
>compiler may try to align the doubles on a 4-byte boundary (or
>possibly another boundary, but 4-bytes is common). In that case, you
>will have to figure out how your C compiler is packing the member and
>emulate that in your dtype. Each of the tuples in the constructor can
>have a third element which represents the byte offset of that member
>from the beginning of the struct.
>
>In [4]: dt2 = dtype([('ctm', uint, 0), ('open', double, 4), ('low',
>double, 12), ('high', double, 20), ('close', double, 28), ('vol',
>double, 36)])
>
>--
>Robert Kern
>
>"I have come to believe that the whole world is an enigma, a harmless
>enigma that is made terrible by our own mad attempt to interpret it as
>though it had an underlying truth."
>  -- Umberto Eco
>_______________________________________________
>Numpy-discussion mailing list
>Numpy-discussion@scipy.org
>http://projects.scipy.org/mailman/listinfo/numpy-discussion



More information about the Numpy-discussion mailing list