使用Boost.Python将Python列表传递给C++向量

10 投票
2 回答
6603 浏览
提问于 2025-04-16 10:44

我该如何把一个Python列表,里面是我自己定义的对象类型ClassName,传递给一个接受vector<ClassName>的C++函数呢?

我找到的最好方法是这样的:示例。不过,遗憾的是,这段代码崩溃了,我也搞不清楚为什么。以下是我使用的代码:

template<typename T>
void python_to_vector(boost::python::object o, vector<T>* v) {
    try {
      object iter_obj = object(handle<>(PyObject_GetIter(o.ptr())));
      return;
      for (;;) {
          object obj = extract<object>(iter_obj.attr("next")());
          // Should launch an exception if it cannot extract T
          v->emplace_back(extract<T>(obj));
      }
    } catch(error_already_set) {
        PyErr_Clear();
        // If there is an exception (no iterator, extract failed or end of the
        // list reached), clear it and exit the function
        return;
    }
}

2 个回答

3

我找到了一种迭代器,可以解决我的问题:

#include <boost/python/stl_iterator.hpp>
template<typename T>
void python_to_vector(boost::python::object o, vector<T>* v) {
    stl_input_iterator<T> begin(o);
    stl_input_iterator<T> end;
    v->clear();
    v->insert(v->end(), begin, end);
}
14

假设你有一个函数,它接收一个 std::vector<Foo> 类型的参数。

void bar (std::vector<Foo> arg)

处理这个问题最简单的方法就是把这个 vector 让 Python 也能用。

BOOST_PYTHON_MODULE(awesome_module)
{
    class_<Foo>("Foo")
        //methods and attrs here
    ;

    class_<std::vector<Foo> >("VectorOfFoo")
        .def(vector_indexing_suite<std::vector<foo> >() )
    ;

    .def("bar", &bar)
}

这样一来,我们就可以在 Python 中把 Foo 对象放进一个 vector 里,然后把这个 vector 传给 bar 函数。

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

撰写回答