DECREFing and PyArray functions in C Extensions

Roger Hansen rogerha at ifi.uio.no
Mon May 29 18:16:26 CEST 2000


* Christian Tismer
> 
> > ..., but what is this:
> > 
> > Py_INCREF(Py_None);  return Py_None;
> > 
> > What's going on there with Py_None?
> 
> The function is supposed to return no value.
> Returning no value in Python means to INCREF and return Py_None.

Yes, a "boilerplate to return None" is the term Guido used, iirc. :-)

Many thanks for the help Christian and Travis! When I have your
attention maybe I could come with yet another example and some
questions. 

Now assume I have an extension where a C function should create and
return a NumPy array.

static PyObject *
foo_retarray(PyObject *self, PyObject *args)
{
  int length, i;
  double x;
  double* a;        
  PyArrayObject *array;

  if(!PyArg_ParseTuple(args, "i", &length))
    return NULL;

  array = (PyArrayObject *) 
    PyArray_FromDims(1, &length, PyArray_DOUBLE);
    
  a = (double*) array->data;
  for (i = 0; i < length; i++) {
    x = (double) i/(length-1);
    a[i] = f(x);
  }

  return PyArray_Return(array);
}

Should I DECREF array here before the return? 
If we rewrite it like this

static PyObject *
foo_retarray2(PyObject *self, PyObject *args)
{
  int length, i;
  double x;
  double* a;        

  if(!PyArg_ParseTuple(args, "i", &length))
    return NULL;

  a = malloc(length*sizeof(double));
  for (i = 0; i < length; i++) {
    x = (double) i/(length-1);
    a[i] = f(x);
  }

  return PyArray_FromDimsAndData(1, &length, PyArray_DOUBLE, (char*) a);
}

I'm sure we don't have to DECREF anything. But is this a good way to
create a NumPy array in C?


better-safe-than-sorry'ly y'rs
Roger



More information about the Python-list mailing list