Search code examples
c++boost-python

std::vector to boost::python::list


I have a method in c++ that gets called from python and needs to return a python list object.

I have already created the method, and its attached to an exposed class and callable from python right now... (it returns void).

So the question is, how do I create a python list from this:

std::vector<std::string> results;

I am not really understanding how the constructor works from this documentation:

http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/list.html

Also... I don't really want to return kind of wrapped vector... I just want to create a new python list with the string values from the vector.

My apologies if this is a duplicate... I found quite a few list to vector questions but I couldn't find any about creating a new python list.

I could expand this question to include some other questions like:

Creating a new python dictionary from a: std::map<std::string, std::string> and so on.


Solution

  • I have this function using iterators to convert std::vector to py::list:

    namespace py = boost::python;
    
    template<class T>
    py::list std_vector_to_py_list(const std::vector<T>& v)
    {
        py::object get_iter = py::iterator<std::vector<T> >();
        py::object iter = get_iter(v);
        py::list l(iter);
        return l;
    }