[C++-sig] Free function returning reference

Kor de Jong k.dejong at geog.uu.nl
Fri Jul 9 10:24:48 CEST 2004

Hi all,

I have some difficulties wrapping free functions which return a
reference (or a pointer) to static variables:

struct Foo {

static Foo d_foo;

void setValue(Foo const& value) {
   d_foo = value;

Foo const& value() {
   return d_foo;

using namespace boost::python;

   def("setValue", &setValue);
   def("value", &value, return_internal_reference<>());

I use the return_internal_reference call policy because I don't
want a copy to be created when value() is called. The first template
argument of return_internal_reference is the owner_arg. According to
the documentation: "If used to wrap a member function, parameter 1 is
the target object (*this)."

But how about wrapping free functions returning references or pointers to
static objects? I would like the Python variables recieving the references
or pointers to be able to use the object but they should not worry about
memory management in this case.

I wonder how the Boost.Python code above should be changed
to get it right. When using the wrapped library from Python a
"python::with_custodian_and_ward_postcall: argument index out of range"
exceptions is thrown when value() is called:

from foopy import *
foo = Foo()

(I appologize if I missed something obvious in the manual.)

Best regards,

More information about the Cplusplus-sig mailing list