Python Boost: polymorphic container?

I have a method (or function) that returns a link to a list of polymorphic objects:

class A {

};
class B : public A {

};


std::list<boost::shared_ptr<A> >& getList();

How to set such a function in boost :: python so that when I repeat in a list in python, I see different types Aand B?

+5
source share
1 answer

First, make sure your classes are truly polymorphic (i.e. have at least one virtual function or virtual destructor). Your example does not do the above, although I'm sure your real use case. Without this, none of the Boost.Python RTTI machines for polymorphism will work.

Then, if you exposed both classes with Boost.Python and registered converters for them shared_ptr:

#include <boost/python.hpp>

namespace bp = boost::python;

BOOST_PYTHON_MODULE(example) {
    bp::class_<A >("A");
    bp::register_ptr_to_python< boost::shared_ptr<A> >();
    bp::class_< B, bp::bases<A> >("B");
    bp::register_ptr_to_python< boost::shared_ptr<B> >();
}

... , , , Python - . - , A, , B.

, , . , , , Boost.Python:

http://www.boost.org/doc/libs/1_49_0/libs/python/doc/v2/indexing.html

, ( " 2" , , Boost.Python), , , .

+4

All Articles