On 01/12/2011 09:03 AM, Matt Bendiksen wrote:
I'm stumped on a problem encountered when trying to return a derived instance 
via a shared_ptr to python. The python instance is always shown as a base class 
and not the subclass that was created, as if the instance was sliced.

        struct A {
        };
        struct B : A {
        };
        shared_ptr<A>  get_a_or_b_instance(bool returnB) {
            return shared_ptr<A>(returnB ? new B() : new A());
        }
…
        def("get_a_or_b_instance", get_a_or_b_instance);
        class_<A, boost::shared_ptr<A>  >("A", init<>())
                ;
        class_<B, bases<A>, boost::noncopyable>("B", init<>())
                ;

And the Python result is always a type A object:

        >>>  type(app.get_a_or_b_instance(False))
        <class 'app.A'>

        >>>  type(app.get_a_or_b_instance(True))
        <class 'app.A'>

Where I would expect the derived instance type B returned from the second call.

I'm using Boost 1.42.0.

Thanks in advance for any help.

You need to either declare B with
"class_<B, boost::shared_ptr<B>, bases<B>"
or do
"register_ptr_to_python< boost::shared_ptr<B> >()"
somewhere in your Python module. The latter will not cause B instances to be stored in a shared_ptr when a Python constructor is called, but it will still enable shared_ptr<B> downcasting on return.

Jim


Matt Bendiksen
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to