Passing Python list to C++ vector using Boost.python

前端 未结 2 1273
慢半拍i
慢半拍i 2021-02-02 03:05

How do I pass a Python list of my object type ClassName to a C++ function that accepts a vector?

The best I found is something

2条回答
  •  失恋的感觉
    2021-02-02 03:58

    Assuming you have function that takes a std::vector

    void bar (std::vector arg)
    

    The easiest way to handle this is to expose the vector to python.

    BOOST_PYTHON_MODULE(awesome_module)
    {
        class_("Foo")
            //methods and attrs here
        ;
    
        class_ >("VectorOfFoo")
            .def(vector_indexing_suite >() )
        ;
    
        .def("bar", &bar)
    }
    

    So now in python we can stick Foos into a vector and pass the vector to bar

    from awesome_module import *
    foo_vector = VectorOfFoo()
    foo_vector.extend(Foo(arg) for arg in arglist)
    bar(foo_vector)
    

提交回复
热议问题