[Numpy-discussion] numpy CAPI questions

Robert Kern robert.kern@gmail....
Sun Oct 19 15:09:46 CDT 2008

On Sun, Oct 19, 2008 at 14:28, Lane Brooks <lbrooks@mit.edu> wrote:
> I am using the numpy CAPI to write an extension module that returns a
> numpy Array from an imaging data source.  I collect the image into a
> buffer that I allocate. I then create numpy Array using the
> PyArray_New(..) function and pass it the buffer.  I then set the
> NPY_OWNDATA flag on the Array because I want the Array to deallocate the
> buffer when it is deleted.  Is that the correct way to do it?  The code
> snippet below is what I wrote, and it seems to be working just fine, but
> I wanted to verify that I am doing things correctly.

Preferably, you should create the array and then use the memory it
allocated as the buffer. Generally, malloc()/free() implementations
are paired, and if you mix-and-match, you're begging for trouble.

> Here are my questions:
> 1. Does NPY_OWNDATA mean that the object will deallocate the memory when
> the object is deleted?  The manual seems to indicate that as such but it
> is not explicitly stated.


> 2. Is my reference counting correct?  Do I need to call the
> PyArray_INCREF() on img?

Personally, I always need to double-check my refcounting with
sys.getrefcount() (which, it should be noted, adds its own reference,
so the correct result for sys.getrefcount(foo()) should be 1). In your
actual code, do you have anything else in the Py_BuildValue()? If you
don't, then you don't need to use Py_BuildValue(); you can just return

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco

More information about the Numpy-discussion mailing list