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

后端 未结 6 669
星月不相逢
星月不相逢 2020-11-27 02:28

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

6条回答
  •  青春惊慌失措
    2020-11-27 03:11

    I use following utility functions to convert from/to stl containers. The trivial sum function illustrates how they are used. Also I found following opensource package which has quite a few conversion utilities: https://github.com/cctbx/cctbx_project/tree/master/scitbx/boost_python

    #include 
    #include 
    #include 
    #include 
    
    namespace bpy = boost::python;
    
    namespace fm {
    
    template 
    bpy::list stl2py(const Container& vec) {
      typedef typename Container::value_type T;
      bpy::list lst;
      std::for_each(vec.begin(), vec.end(), [&](const T& t) { lst.append(t); });
      return lst;
    }
    
    template 
    void py2stl(const bpy::list& lst, Container& vec) {
      typedef typename Container::value_type T;
      bpy::stl_input_iterator beg(lst), end;
      std::for_each(beg, end, [&](const T& t) { vec.push_back(t); });
    }
    
    bpy::list sum(const bpy::list& lhs, const bpy::list& rhs) {
      std::vector lhsv;
      py2stl(lhs, lhsv);
    
      std::vector rhsv;
      py2stl(rhs, rhsv);
    
      std::vector result(lhsv.size(), 0.0);
      for (int i = 0; i < lhsv.size(); ++i) {
        result[i] = lhsv[i] + rhsv[i];
      }
      return stl2py(result);
    }
    
    } // namespace fm
    
    BOOST_PYTHON_MODULE(fm)
    {
      bpy::def("sum", &fm::sum);
    }
    

提交回复
热议问题