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

Travis Oliphant oliphant.travis at ieee.org
Tue Dec 12 12:40:15 CST 2006


Lou Pecora wrote:
> I've done this two ways.  Which is better or safer?
>
> Say I'm passing a NumPy array (float) to a C
> extension.  One way to "parse" it is (ignoring checks
> on return values, etc. for now),
>
>   PyArrayObject *mat;
>   PyArg_ParseTuple(args, "O!", &PyArray_Type, &mat);
>
> 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).

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.

> I've done both.  Pointing C arrays to the resulting
> PyArrays' data works fine, but I fear one way or the
> other might be courting disaster.
>   
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



More information about the SciPy-user mailing list