使用Pyth.python将Python列表传递给C++矢量

2024-04-19 07:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

< >我如何将对象类型的{Pyth}{Cd1}}传递给接受^ {< CD2>}的C++函数?

我找到的最好的东西是这样的:example。不幸的是,代码崩溃了,我似乎不明白为什么。我用的是:

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

Tags: the对象anobj类型returnobjectexception
2条回答

找到一个解决我问题的迭代器:

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

假设有一个函数需要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中,我们可以将Foos粘贴到vector中,并将向量传递给bar

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

相关问题 更多 >