[C++-sig] How to return embedded Python object

Roman Yakovenko roman.yakovenko at gmail.com
Tue Apr 3 19:48:22 CEST 2007


On 4/2/07, Koen Van Herck <koen_van_herck at yahoo.com> wrote:
>
>  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.
>

I think you should use "return_self" call policy(
http://boost.org/libs/python/doc/v2/return_arg.html#return_self-spec )


-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070403/46a47399/attachment.htm>


More information about the Cplusplus-sig mailing list