Passing a Python list to a C ++ vector using Boost.python

How to pass a Python list of my ClassName object ClassName to a C ++ function that accepts vector<ClassName> ?

The best I have found is something like this: an example . Unfortunately, the code crashes and I cannot understand why. Here is what I used:

 template<typename T> void python_to_vector(boost::python::object o, vector<T>* v) { try { object iter_obj = object(handle<>(PyObject_GetIter(o.ptr()))); return; for (;;) { object obj = extract<object>(iter_obj.attr("next")()); // Should launch an exception if it cannot extract T v->emplace_back(extract<T>(obj)); } } catch(error_already_set) { PyErr_Clear(); // If there is an exception (no iterator, extract failed or end of the // list reached), clear it and exit the function return; } } 
+7
source share
2 answers

Assuming you have a function that takes std::vector<Foo>

 void bar (std::vector<Foo> arg) 

The easiest way to handle this is to open python vector .

 BOOST_PYTHON_MODULE(awesome_module) { class_<Foo>("Foo") //methods and attrs here ; class_<std::vector<Foo> >("VectorOfFoo") .def(vector_indexing_suite<std::vector<foo> >() ) ; .def("bar", &bar) } 

So now in python we can insert Foo into vector and pass the vector to bar

 from awesome_module import * foo_vector = VectorOfFoo() foo_vector.extend(Foo(arg) for arg in arglist) bar(foo_vector) 
+10
source

Found an iterator that solves my problem:

 #include <boost/python/stl_iterator.hpp> template<typename T> void python_to_vector(boost::python::object o, vector<T>* v) { stl_input_iterator<T> begin(o); stl_input_iterator<T> end; v->clear(); v->insert(v->end(), begin, end); } 
+3
source

All Articles