boost Using boost.python Wrapping std::vector in boost.python

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

If a function returns a std::vector type, and it is exposed to Python directly like

std::vector<float> secondMethod() {
    return std::vector<float>();
}

BOOST_PYTHON_MODULE(CppProject) {
    boost::python::def("getEmptyVec", secondMethod);
}

then when the functions gets called Python will tell you No to_python (by-value) converter found for C++ type: std::vector<float, std::allocator<float> >, because Python needs to know how to deal with std::vector.

Fortunately boost.python has provided a wrapper funciton for us in vector_indexing_suite.hpp. The returning value can be handled as a FloatVec object whose element can be accessed by the [] operator, by exposing the corresponding wrapper function as following.

std::vector<float> secondMethod() {
    return std::vector<float>();
}

BOOST_PYTHON_MODULE(CppProject) {
    // wrapper function
    class_<std::vector<float> >("FloatVec")
        .def(vector_indexing_suite<std::vector<float> >());
    boost::python::def("getEmptyVec", secondMethod);
}

The result can be further converted into a Python list or Numpy array simply by calling list() and numpy.asarray().



Got any boost Question?