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

末鹿安然 提交于 2019-11-29 21:26:00

To make your C++ method accept Python lists you should use boost::python::list

void massadd(boost::python::list& ns)
{
    for (int i = 0; i < len(ns); ++i)
    {
        add(boost::python::extract<double>(ns[i]));
    }
}

Here's what I use:

#include <boost/python/stl_iterator.hpp>

namespace py = boost::python;

template< typename T >
inline
std::vector< T > to_std_vector( const py::object& iterable )
{
    return std::vector< T >( py::stl_input_iterator< T >( iterable ),
                             py::stl_input_iterator< T >( ) );
}

Should you find the input type (py::object) too liberal, feel free to specify stricter types (py::list in your case).

Based on the above answers I created an example of accessing python lists in C++ as well as returning a python list from a C++ function:

#include <boost/python.hpp>
#include <string>

namespace py = boost::python;

// dummy class
class drow{
    public:
        std::string word;
        drow(py::list words);
        py::list get_chars();
};

// example of passing python list as argument (to constructor)
drow::drow(py::list l){
    std::string w;
    std::string token;
    for (int i = 0; i < len(l) ; i++){
        token = py::extract<std::string>(l[i]);
        w += token;
    }
    this -> word = w;
}

// example of returning a python list
py::list drow::get_chars(){
    py::list char_vec;
    for (auto c : word){
        char_vec.append(c);
    }
    return char_vec;
}

// binding with python
BOOST_PYTHON_MODULE(drow){
    py::class_<drow>("drow", py::init<py::list>())
        .def("get_chars", &drow::get_chars);
}

For a build example and a test python script take a look here

Thank you Arlaharen & rdesgroppes for the pointers (pun not intended).

To get automatic conversion from python lists, you have to define a converter, which

  1. checks if the list is convertible to your type (i.e. that it is a sequence; additionally, you can also check whether all elements are of required type, but that can be handled in the second step as well)
  2. returns the new object, if the first step succeeded; throw exception if a sequence element is not convertible to what you need.

I can't find now anything else than my code, you can copy&paste this template (it is specialized at the end of that file for various contained types).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!