[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


Hello,
 
I've got the following class Foo, which is noncopyable, exposed to Python:
 
    class Foo: ::boost::noncopyable
    {
    public:
        ::boost::python::object myself()
        {
            return ::boost::python::object(::boost::python::ptr(this));
        }
    };
    
    ::boost::python::class_< Foo, ::boost::noncopyable > ("Foo")
        .def("myself", &Foo::myself)
    ;
 
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 
    return ::boost::python::object(this);
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...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070402/1600f395/attachment.htm>


More information about the Cplusplus-sig mailing list