[C++-sig] create boost array from a Numpy PyArray without copying data?

Ravi lists_ravi at lavabit.com
Fri Jan 23 16:36:55 CET 2009


On Friday 23 January 2009 04:44:43 Sebastian Walter wrote:
> > In the code you posted this time, incref() is required so that someone
> > owns a reference to the array object. What I don't know off the top of my
> > head is whether you need an incref in the constructor of A and a decref
> > in the destructor of A.
>
> This is also something I wondered about.
> I guess it's better incref/decref them to be on the save side, right?

IIRC, PyArray_SimpleNewFromData gives you a new reference. If that is correct, 
you will need to decref() it in the destructor of A so that python can clean 
up the numpy array (without touching your global data). What is the value of 
the flag NPY_OWNDATA after the call to PyArray_SimpleNewFromData? That should 
tell you whether python will attempt to free your global data structure.

> ------------------- test.py ----------------
> from _test import *
> import sys
>
> def test_my_array():
>         a = A()
>         print 'a.my_array=',a.my_array
>         print 'sys.getrefcount(a)=',sys.getrefcount(a)
>         print 'sys.getrefcount(a.my_array)=',sys.getrefcount(a.my_array)
>
>
> if __name__ == "__main__":
>         test_my_array()
>
> ------------ end test.py -------------
> I get the output
>
> ----------- output -------------
>
> walter at wronski$ python test.py
> a.my_array= [ 1.  2.  3.]
> sys.getrefcount(a)= 2
> sys.getrefcount(a.my_array)= 2
>
> ----------- end output --------
>
> Ermm, is that good?
> I expected that the refcount would be 1 and not 2.

I don't know. I generally avoid these issues by writing custom converters and 
letting boost.python handle reference counting. Perhaps someone else on the 
list might be able to help.

Regards,
Ravi




More information about the Cplusplus-sig mailing list