Python Boost and shared_ptr vectors

I read how to set regular vectors for python in boost python, but I want to know how to set and use a vector. For example, I have a shared_ptrs vector as follows:

std::vector<shared_ptr<StatusEffect> > Effects; 

Based on material for exhibiting vectors, I should be able to expose this type of class. I want to know how can I add to it? How to create instances of shared_ptr<StatusEffect> , since I donโ€™t have access to the new one, and shared_ptr can point to several derived types, which makes adding a static creation method to each class a little tedious.

Does anyone have pointers or can suggest how to do this? Finding a good example for boost :: python for what I want to do was difficult

Thanks in advance

+7
source share
4 answers

See Pointers and smart pointers for an example.

+1
source

You mentioned that the creation method (constructor) for each class would be a little tedious, but I think you need to.

0
source
 struct A { int index; static shared_ptr<A> create () { return shared_ptr<A>(new A); } std::string hello () { return "Just nod if you can hear me!"; } }; BOOST_PYTHON_MODULE(my_shared_ptr) { class_<A, shared_ptr<A> >("A",boost::python::init<>()) .def("create",&A::create ) .staticmethod("create") .def("hello",&A::hello) .def_readonly("index",&A::index) ; boost::python::class_<std::vector<shared_ptr<A>>>("PyVec") .def(boost::python::vector_indexing_suite<std::vector<shared_ptr< A>>,true >()); } 

The argument "truth" is important!

0
source

You can partially bind boost::shared_ptr<StatusEffect> by omitting the construct just fine with Boost.Python (use boost::python::no_init ). To have a similar mechanism with std::shared_ptr<StatusEffect> , you must also define a free boost::get_pointer<T>() function with T = std::shared_ptr<U> as described in this other SO thread . Here is a sketch of a workable solution:

 #include <boost/python.hpp> #include <memory> ... namespace boost { template<class T> T* get_pointer(std::shared_ptr<T> p) { return p.get(); } } BOOST_PYTHON_MODULE(yourmodule) { using namespace boost::python; class_<StatusEffect, std::shared_ptr<StatusEffect>, boost::noncopyable>("StatusEffect", no_init); class_<std::vector<std::shared_ptr<StatusEffect> > >("StatusEffectVector") .def(boost::python::vector_indexing_suite<std::vector<shared_ptr<StatusEffect>>, true>()); } 
0
source

All Articles