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

Lou Pecora lou_boog2000 at yahoo.com
Tue Dec 12 18:53:07 CET 2006

Thanks for the answers, Chris.  A few comments and
questions beyond what I asked and you answered:

--- Christopher Barker <Chris.Barker at noaa.gov> wrote:

> Lou,
> This type of question is best posed on the numpy
> list:

Ah, yet another mailing list to join.  Sigh.  :-) 

> Lou Pecora wrote:
> >>   PyArrayObject *mat;
> >>   PyArg_ParseTuple(args, "O!", &PyArray_Type,
> &mat);
> If you do this, you then need to check and see if
> the array that got 
> passed in has the properties you want: size, shape,
> type.

I do, but I don't know how to check in Python for
contiguous.  I will search for that.  Should be a way.
> >>   PyObject *Pymat;
> >>   PyArrayObject *mat;
> >>   PyArg_ParseTuple(args, "O", &Pymat);
> >>  
> mat=PyArray_ContiguousFromObject(objin,NPY_DOUBLE,
> >> 2,2);
> I've always used PyArray_ContiguousFromObject,
> because then it does all 
> the checking for me, and it allows my code to accept
> anything that can 
> by turned into a numpy array.

Got it.  That's what I suspected.  

> >> 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?
> What it does is convert whatever you pass in to a
> Contiguous array. If 
> it already is a contiguous array, then it returns
> itself (I think -- 
> check the docs). There is probably something like:
> PyArray_FromObject
> That does not guarantee contiguous, if you don't
> need that.

That can lead to a problem.  If I have a C extension
in which I expect to operate on the array data in
place, then passing a non-contiguous array will cause
a new data set to be developed (new memory, I would
assume) and the original array would not be changed in
place by my C operations.  Then I have a problem.  The
original array is unchanged, but I assume it has been
changed.  In this case I would want a check on whether
the input array is contiguous and an exception raised
if not ... or something to say there's a
data-structure problem.

-- Lou Pecora
      My views are my own.

Yahoo! Music Unlimited
Access over 1 million songs.

More information about the Pythonmac-SIG mailing list