[SciPy-user] [SciPy-dev] C API

Travis Oliphant oliphant.travis at ieee.org
Mon Nov 28 22:25:01 CST 2005


Nariman Habili wrote:

>Travis, I have purchased a copy of your "Guide to SciPy: Core System", some 
>sections seem to be missing, for example section 13.2, "Using the Array 
>iterator in C". I would appreciate it if you could explain to me how I can 
>use the array iterator.
>  
>

The iterator object makes it easy to walk through an entire ndarray or 
move to a particular location.
It is general purpose and so possibly slower on 2-d images than one of 
the other macros I'll explain next

Suppose array is your PyArrayObject * variable.

PyArrayIterObject *iter;

iter = (PyArrayIterObject *)PyArray_IterNew(array);

while (iter->index < iter->size) {
    /*  iter->dataptr  points to the current element of the array -- 
recast it to the appropriate type if you want
    */
    PyArray_ITER_NEXT(iter);
}

You can also use PyArray_ITER_GOTO(iter, ind)  where ind is an array of 
intp integers giving the index into the array (available in the latest 
SVN version of scipy core).

If you just want to access a particular  i,j location in a 2-d array, 
then use

ptr = (<yourtype> *)PyArray_GETPTR2(obj, i, j);

This could be used in a dual for-loop to process the data in an image:

for (i=0; i<PyArray_DIM(obj, 0); i++) {
      for (j=0; j<PyArray_DIM(obj, 1); j++) {
            /* Change the type here depending on your array data type */
            valptr = (double *)PyArray_GETPTR2(obj, i, j);
            /* Now do something with valptr  --- you could also insert 
into a specific section of the
                array using the same pointer */
      }
}


Best regards,

-Travis






More information about the SciPy-user mailing list