[Numpy-discussion] numpy CAPI questions

Lane Brooks lbrooks@MIT....
Mon Oct 20 16:13:51 CDT 2008


Travis E. Oliphant wrote:
> 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
>   
Thanks for all this valuable feedback.  I read your blog post and like 
the idea but not the overhead.  I guess my initial approach of doing a 
memory handoff to the numpy Array was a bit naive.  It seems to be 
working, but I guess that is because numpy uses free to deallocate memory?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20081020/fbb0e33a/attachment.html 


More information about the Numpy-discussion mailing list