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

后端 未结 4 2101
庸人自扰
庸人自扰 2020-12-24 01:47

Finally I\'m able to use std::vector in python using the [] operator. The trick is to simple provide a container in the boost C++ wrapper which handles the internal vector s

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 02:26

    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 
    #include 
    
    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(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", py::init())
            .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).

提交回复
热议问题