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

后端 未结 6 664
星月不相逢
星月不相逢 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:19

    boost::python already includes functionality for wrapping vectors and maps. Here's sample code for vectors, as you can see both passing and returning lists is quite simple:

    // C++ code
    typedef std::vector MyList;
    class MyClass {
      MyList myFuncGet();
      void myFuncSet(const Mylist& list);
      //       stuff
    };
    
    // Wrapper code
    
    #include 
    
    using namespace boost::python;
    
    
    BOOST_PYTHON_MODULE(mymodule)
    {
        class_("MyList")
            .def(vector_indexing_suite() );
    
        class_("MyClass")
            .def("myFuncGet", &MyClass::myFuncGet)
            .def("myFuncSet", &MyClass::myFuncSet)
            ;
    }
    

    Maps are very similar to vectors and are described in this post: Boost::Python- possible to automatically convert from dict --> std::map?

    Unfortunately boost::python does not currently include facilities for wrapping lists. You can create the wrapper manually, but I'm out of time for this answer. I can post it today or tomorrow. I'd appreciate a new question about this particular problem, because the answer will be quite extensive and is probably outside of the scope of this post. I'd just avoid lists and use vectors instead.

提交回复
热议问题