[C++-sig] Callbacks with internal references as arguments
Daniel Lewis
actiondan at gmail.com
Sat Feb 5 22:09:55 CET 2005
Hello,
I'm trying to write a module using boost::python that can deliver
callbacks, but I'm having trouble with declaring my intentions with
regards to object ownership. A simple example of what I am trying to
achieve is this:
struct Foo { };
struct Bar {
Foo& get_foo() { return foo; }
void foo_callback() { callback(foo); }
Foo foo;
object callback;
};
BOOST_PYTHON_MODULE (foobar) {
class_<Foo>("Foo", init<>());
class_<Bar>("Bar", init<>())
.def("get_foo", &Bar::get_foo, return_internal_reference<>())
.def("foo_callback", &Bar::foo_callback)
.def_readwrite("callback", &Bar::callback);
}
So when calling Bar::get_foo() from Python, I get the desired behaviour:
the same Python object is returned every time, and Bar::foo is not destroyed
when the Python object is.
When using Bar::foo_callback(), like this:
def callback(foo):
print foo
bar.callback = callback
bar.foo_callback()
I get a different object, and ~Foo() is called when the Python object is
destroyed.
Is there any way to achieve the "internal reference" behaviour when
delivering the object as a callback argument?
Thanks,
Dan.
More information about the Cplusplus-sig
mailing list