0

My question is basically the same as std::vector to boost::python::list. The difference is that I only need to read data from C++ in python side.

Naively, I could build a new C++ class holding a pointer and forward all the required attributes and then expose this new class to python. Is there a better(simpler or systematic) way to get a python 'list' (not really a list since setter is not allowed) without copy the underlying data?

Ma Ming
  • 1,765
  • 2
  • 12
  • 15

1 Answers1

1

If you do not want to convert std::vector to boost::python::list. Then it can be possible if you pass the size of vector to python side and iterate the function with argument as index to get the element of vector to python side.

in cpp:

class vc
{
    private:
        vector <int> vec ;
    public: 
        vc(){};
        void set_vector();
        int vector_size();
        int vector_iterator(int index);
        ~vc(){};
}

void vc::set_vector()
{
    for(int i=0;i<10;i++)
        this->vec.push_back(i);
}

int vc::vector_size()
{   
    return this->vec.size();
}

int vc::vector_iterator(int index)
{   
    if(this->vec.size()> index)
        return  this->vec[index];
    return 0;
}

BOOST_PYTHON_MODULE(vector_imp)  
{  
    class_<vc>("vc", init<>())
        .def("set_vector",&vc::set_vector)
        .def("vector_size",&vc::vector_size)  
        .def("vector_iterator",&vc::vector_iterator)
    ;  
}

in python:

import vector_imp as vect
    vc_obj = vect.vc()
    vc_obj.set_vector()
    v_size = vc_obj.vector_size()
    for i in range(0,v_size):
        element = vc_obj.vector_iterator(i)
        print element
HarshGiri
  • 408
  • 2
  • 12