[SciPy-user] accessing contents of complex numpy array from pyrex

Robert Kern robert.kern@gmail....
Mon Jan 7 12:41:00 CST 2008

Lev Givon wrote:
> Does anyone know how to access the elements of a 1-D numpy array
> containing complex values from within a function written in pyrex?
> Since pyrex currently doesn't provide a straightforward interface to
> complex data types, I was wondering whether there is some way to
> access the real and imaginary portions of each element in the data
> block of the array directly.

One way would be to define a my_complex struct in a .h file, expose it in Pyrex, 
and cast the data pointer to <my_complex*>:

#### my_complex.h

typedef struct {
     double real, imag;
} my_complex;

#### EOF

#### complex_arrays.pyx

# E.g. from numpy/random/mtrand/numpy.pxi
include "numpy.pxi"

cdef extern from "my_complex.h":
     cdef struct my_complex:
         double real, imag

def foo(numpy.ndarray complex_array):
     cdef my_complex* c_complex_array

     c_complex_array = <my_complex*>PyArray_DATA(complex_array)
     # ...

#### EOF

Alternatively, you could get the .real and .imag arrays at the Python level, 
cast them as <numpy.ndarray> and access the data that way. Of course, these will 
be discontiguous, so you will have to take the stride into account.

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

More information about the SciPy-user mailing list