[Pythonmac-SIG] [SciPy-user] Best/Safest way to parse NumPy array in C extension?
Christopher Barker
Chris.Barker at noaa.gov
Tue Dec 12 18:33:17 CET 2006
Lou,
This type of question is best posed on the numpy list:
http://projects.scipy.org/mailman/listinfo/numpy-discussion
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.
>> 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.
>> 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.
By the way, I think these are the old Numeric names, which numpy has a
compatibility layer for, but you may want to use the new, numpy ones.
There are a lot, but most are special cases of:
Py_Array_FromAny
This is well documented in the Numpy book, I'm not sure about what's online.
>> 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.
>>
>> BTW, I do other checks on dimension, type, etc., but
>> I left those out here for clarity. (I hope.)
If you do all those checks, you're OK, but do make sure you are not
assuming contiguous, if you haven't forced it -- that can slip through
testing.
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the Pythonmac-SIG
mailing list