DECREFing and PyArray functions in C Extensions

Travis Oliphant olipt at mayo.edu
Mon May 29 03:35:07 CEST 2000


> 
> OK! Lets say I have a Python program with a NumPy array and a loop,
> and for efficiency reasons I decide to write the loop as an extension,
> like this:
> 
> static PyObject * 
> foo(PyObject *self, PyObject* args)
> {
>   PyArrayObject *array;
>   double* a;            /* C ptr to the NumPy array data field */
> 
>   if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array)) {
>     return NULL;  /* Error indicator */
>   }
> 
>   ...   /* Check if array has right dimension, etc. */
> 
>   n = array->dimensions[0];    /* Get the length of the array */
>   a = (double*) array->data;   /* Set the pointer to the NumPy data */
> 
>   for (i=0; i<n; i++) {
>     x = (double) i/(n-1);
>     a[i] = f(x);
>     /* more general: *(array->data+i*array->strides[0]) = f(x) */
>   }
> 
>   Py_INCREF(Py_None);  return Py_None;
> }   
> 
> where f is some function. I don't need to DECREF array in this
> example since PyArg_ParseTuple does not increase the reference count,
> right?

No DECREF needed, since no call to PyArray_XXXXX was made.  You are
using a borrowed reference from the PyArg_ParseTuple command.

You haven't missed a beat...

-Travis





More information about the Python-list mailing list