[C++-sig] Retrieving lvalues using custom converters (numpy 1-D converters attached)

Ravi lists_ravi at lavabit.com
Thu Oct 2 21:54:46 CEST 2008

On Thursday 02 October 2008 15:22:32 Neal Becker wrote:
> Do I understand correctly, that when returning a ublas::vector to python,
> lifetime management is not provided?  That is, nothing will ever destruct
> the ublas::vector, resulting in a memory leak?

Yes. However, you can use any of the standard return value policies from 
boost.python to manage the lifetime of an array returned to python; if you use 
copy_const_reference and return the array by value from your function, any 
decent optimizing compiler would optimize away the copy.

There are 4 main use cases:

1. A python array is passed into your function (and perhaps you modify it); no 
lifetime management is needed here.

2. A C++ array is exposed as a member of some other class; the lifetime of the 
python member is tied to the lifetime of the C++ object and the usual caveats 

3. A C++ array is returned from a function by reference; in this case, the 
usual return value policies can be used to manage the Python object lifetime.

4. A C++ array is returned from a function by value; this case is the same as 
the preceding one.

Note that there is no use case in which a python array is passed back out of a 
C++ function. The rationale is that python arrays can be created only in 
python in which case you already have a reference in python. If you create a 
python array in C++, you are on your own. In that case, it is not terribly 
hard to use the provided converter to get a numpy ublas array; you could 
simply write the trivial to_python converter using the provided get_array() 


More information about the Cplusplus-sig mailing list