[Numpy-discussion] C-extensions to numpy - a little help is needed

Travis Oliphant oliphant.travis at ieee.org
Sun Mar 12 15:04:01 CST 2006


Mads Ipsen wrote:
> Hey,
>
> I am trying to understand how to write numpy extensions, in order to be
> able to do various things fast, that I need in my own apps. I have looked
> at the examples from the Numeric package, which I managed to get working
> with numpy, so I guess my questions holds for this forum.
>
> There's one detail, that I don't understand in the examples provided with
> the Numeric documentation, namely the use of
>
>     Py_DECREF(...)
>
> which is used in the first example but not in the last. Let me be more
> specific:
>   
There are several problems with the example in the documentation that 
lead to memory leaks.  It
needs to be fixed. 

You are correct that

Py_DECREF(matrix);
Py_DECREF(vector);

is needed before returning control back to Python.

In addition, the error-handling code (when return NULL is encountered) 
also needs to make sure that arrays that have been created get destroyed 
using Py_DECREF(...) before returning from the function.   This is often 
done using an err:  label and the goto command in C.

Then, at the error label  Py_XDECREF(...) is used which does nothing if 
the argument is NULL, but otherwise DECREF's the object (destroying it 
if it's the only reference).


So, this example is flawed.   I think that it's come up before but I 
don't recall the list discussion.  But, obviously nothing was done to 
change the documentation.

-Travis






More information about the Numpy-discussion mailing list