DECREFing and PyArray functions in C Extensions
Roger Hansen
rogerha at ifi.uio.no
Sun May 28 09:38:48 EDT 2000
* Travis Oliphant
[snip]
> This is still my advice, but I would reword it:
>
> Every PyArrayObject that you successfully receive from a
> PyArray_XXXXXX call has an increased reference count (you own a
> reference). Unless you are returning the object to the user (using
> return PyArray_Return(obj) or PyArray_BuildValue with the "N"
> construct) you must DECREF the object before leaving the subroutine
> or you will create a memory leak..
[snip]
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?
Suddenly-wondering-if-I've-messed-it-up'ly y'rs
Roger
More information about the Python-list
mailing list