[C++-sig] How to return embedded Python object
Koen Van Herck
koen_van_herck at yahoo.com
Mon Apr 2 17:30:15 CEST 2007
I've got the following class Foo, which is noncopyable, exposed to Python:
class Foo: ::boost::noncopyable
::boost::python::class_< Foo, ::boost::noncopyable > ("Foo")
I create a Foo() instance from Python:
>>> f = Foo()
and now I want the myself() method to return a Python object pointing to the
same C++ object. With the code above, I can do:
>>> m = f.myself()
and use m as if it were f (though f==m returns False, but that's not an
issue for me).
However, if I delete f, or f goes out of scope, the C++ instance is deleted
and m points to a deleted C++ object.
If I replace the return statement with
I get a runtime error: "No to_python (by-value) converter found for C++
type: class Foo",
which makes sense because the class is noncopyable.
What is the correct way to return the embedded Python object in the myself()
method, such that reference counting works, i.e., the C++ instance is
deleted when both f and m objects are deleted.
My actual use case does not simply return 'this', but returns a list of
class instance which hold a pointer to the Foo instance as a data member.
Thanks for any help,
Koen Van Herck.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Cplusplus-sig