[Numpy-discussion] numpy CAPI questions

Travis E. Oliphant oliphant@enthought....
Mon Oct 20 12:15:56 CDT 2008


Lane Brooks 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.
>
>   
NPY_OWNDATA means the object will try to deallocate the memory (make 
sure it was allocated with the same allocator as NumPy uses).  
Otherwise, you will need to set up another approach as I showed in my 
blog posting several weeks ago.

Also, don't use Py_BuildValue with "O" as it will create another 
reference so that img will have an extra reference to it when it is 
returned to Python.  Use "N" instead.

However, in this case you don't need to use Py_BuildValue at all because 
you are returning only one array.

The PyArray_UpdateFlags call is not used for changing NPY_OWNDATA.  It 
is only useful for changing FORTRAN, CONTIGUOUS, ALIGNED, and WRITEABLE 
flags which are convenience flags.  This call does the check first and 
then sets the state of the flag to reflect the actual situation for the 
array.

Instead use

PyArray_FLAGS(arr) |= NPY_OWNDATA;

-Travis



More information about the Numpy-discussion mailing list