[SciPy-user] Best/Safest way to parse NumPy array in C extension?

Lou Pecora lou_boog2000 at yahoo.com
Tue Dec 12 13:02:15 CST 2006

Thanks for the feedback, Travis.  Chris Barker gave
some similar answers, but you both provided
non-overlapping replies.  A few questions:

--- Travis Oliphant <oliphant.travis at ieee.org> wrote:
> --- Lou Pecora wrote:
> > or is this better,
> >
> >   PyObject *Pymat;
> >   PyArrayObject *mat;
> >   PyArg_ParseTuple(args, "O", &Pymat);
> >  
> mat=PyArray_ContiguousFromObject(objin,NPY_DOUBLE,
> > 2,2);
> It totally depends on what you want.  If you just
> pass in the array, 
> then you will have to make sure that your code can
> handle the full 
> generality of the ndarray (or else have checks on
> the Python-side).

I will have to learn how to check for contiguous in

> Ndarrays can be arbitrarily strided, mis-aligned,
> out of machine order, 
> and of arbitrary data-type.
> > The latter appears to have the constraint that the
> > array be contiguous.  Or is that an illusion and
> it's
> > saying it _expects_ a Python object that has
> > contiguous data?
> >   
> No, the latter will convert an array to be
> contiguous, in machine 
> byteorder (and aligned) and convert it to DOUBLE
> type.   So, if your 
> code only handles that kind of array, then use the
> conversion function.

Does this conversion mean that the array now has new
data in contiguous form so that operations done on the
data in the C extension (in place) will show up in
that array when I return to the Python caller?  (I am
assuming I passed the array in as an arg to the C
extension in the first place.)

> It will be fine until you give it a discontiguous
> array, in the wrong 
> byte-order, and possibly mis-aligned (coming from a
> field of another 
> array).
> -Travis

Got it.  It seems that NumPy array creators like
zeros(...) return continguous data. Is that always

-- Lou Pecora
      My views are my own.

Need a quick answer? Get one in minutes from people who know.
Ask your question on www.Answers.yahoo.com

More information about the SciPy-user mailing list