简体   繁体   English

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

[英]Passing Python list to C++ vector using Boost.python

How do I pass a Python list of my object type ClassName to a C++ function that accepts a vector<ClassName> ? 如何将对象类型ClassName的Python列表传递给接受vector<ClassName>的C ++函数?

The best I found is something like this: example . 我找到的最好的是这样的: 例子 Unfortunately, the code crashes and I can't seem to figure out why. 不幸的是,代码崩溃了,我似乎无法弄清楚原因。 Here's what I used: 这是我用过的东西:

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;
    }
}

Assuming you have function that takes a std::vector<Foo> 假设你有一个带std::vector<Foo>函数

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

The easiest way to handle this is to expose the vector to python. 处理此问题的最简单方法是将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)
}

So now in python we can stick Foo s into a vector and pass the vector to bar 所以现在在python中我们可以将Foo s粘贴到一个vector并将vector传递给bar

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

Found an iterator that solves my problem: 找到一个解决我的问题的迭代器:

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM