Boost.Python and C ++ std :: vector pointers

I use Boost.Python to create a wrapper for my C ++ library, and I am having problems; searching the site all day has not yielded any results. For example, I have the following code:

class Base { public: virtual void func() = 0; }; class Derived : public Base { public: virtual void func() { cout << "Derived::func()"<< endl; } }; // wrapper for Base struct BaseWrapper : Base, python::wrapper<Base> { virtual void func() { this->get_override("func"); } }; Base* makeDerived() { return new Derived; } vector<Base*>* makeDerivedVec() { vector<Base*> *v = new vector<Base*>; v->push_back(new Derived); v->push_back(new Derived); v->push_back(new Derived); return v; } BOOST_PYTHON_MODULE(mylib) { // export Base class_<BaseWrapper, noncopyable>("Base") .def("func", pure_virtual(&Base::func)); class_<vector<Base*> >("BasePtrVec") .def(vector_indexing_suite<vector<Base*> >()); // export Derived class_<Derived, bases<Base> >("Derived") .def("func", &Derived::func); // export makeDerived() def("makeDerived", &makeDerived, return_value_policy<manage_new_object>()); // export makeDerivedVec() def("makeDerivedVec", &makeDerivedVec, return_value_policy<manage_new_object>()); } 

So, I will compile it, import into python and try the following:

b = mylib.Base () b.func ()

d = mylib.makeDerived () d.func ()

The first line, as expected, throws an exception saying that b.func () is purely virtual, and the second line outputs

Derived :: FUNC ()

And this is normal.

But the code

 dlist = mylib.makeDerivedVec() for d in dlist: d.func() 

does not work, and Python throws an exception:

 TypeError: No to_python (by-value) converter found for C++ type: Base* 

Why does it correctly process the base * returned by makeDerived () and refuses to work with the base * contained in std :: vector? How can I make it work?

+6
source share
1 answer

You can fix this by registering Base* as a type that you can use to point to BaseWrapper* :

 class_<BaseWrapper, noncopyable, Base*>("Base") .def("func", pure_virtual(&Base::func)); 

But that seems to mean that Base cannot have a pure virtual function ...

+3
source

Source: https://habr.com/ru/post/901700/


All Articles