[SciPy-user] numpy array in ctype struct

Travis E. Oliphant oliphant@enthought....
Mon Jan 21 13:17:36 CST 2008

Rob Hetland wrote:
> On Jan 15, 2008, at 7:04 PM, Paul Kienzle wrote:
>> Instead of creating the ctypes struct I just used numpy to create a  
>> scalar
>> of the correct structure.  I wrapped it in a class so that I could  
>> reference
>> the fields directly as e.g., instance.A.  I used a factory function
>> for generating the class from the structure definition since I will  
>> need
>> to wrap several structures.
>> I'm attaching cstruct.py and embedarray.c where I demonstrate this.
>> I'm particularly pleased that I can assign a 4x4 array to instance.A
>> and it just works!
>> The ctypes docs talk about possible alignment issues for the  
>> structs on
>> some architectures.  They say it the ctypes follows the conventions of
>> the compiler which created it.  I haven't checked if this will be a
>> problem with the numpy solution you outline above.
>> <embedarray.c><cstruct.py>
> How do you pass ndarrays of arbitrary size.  I would like to have  
> some C code like:
> extern void bar(double **data, int L, int M) {
>      ...
> }
> The code needs to pass the array on to another library as a **double,  
> and I cannot seem to get ctypes to pass a 2 dimensional array to the  
> subroutine.  Arrays if fixed size seem to work fine, and single  
> dimensional *doubles also work fine, even when passing  
> multidimensional numpy.ndarrays.
> But, how to pass an arbitrary (two-dimensional) numpy.ndarray as a  
> **double?

You might find PyArray_AsCArray useful.   It takes a NumPy array and 
produces the needed pointers to allow accessing the array as a C-style 

It works for 1-, 2-, and 3-d arrays.  There are old Numeric API's that 
do similar things specifically for 2-d and 1-d arrays.

You need to make sure and use PyArray_Free to clean up the pointers 
created to simulate the pointer-to-pointers approach.

Best regards,

-Travis O.

> -Rob
> ----
> Rob Hetland, Associate Professor
> Dept. of Oceanography, Texas A&M University
> http://pong.tamu.edu/~rob
> phone: 979-458-0096, fax: 979-845-6331
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user

More information about the SciPy-user mailing list