使用Boost.python将Python列表传递给C ++向量 [英] Passing Python list to C++ vector using Boost.python
本文介绍了使用Boost.python将Python列表传递给C ++向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将对象类型ClassName
的Python列表传递给接受vector<ClassName>
的C ++函数?
How do I pass a Python list of my object type ClassName
to a C++ function that accepts a vector<ClassName>
?
我发现的最好的是这样的:示例一个>.不幸的是,代码崩溃了,我似乎无法弄清楚为什么.这是我用的:
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;
}
}
推荐答案
假定您具有采用std::vector<Foo>
void bar (std::vector<Foo> arg)
处理此问题的最简单方法是将vector
暴露给python.
The easiest way to handle this is to expose the vector
to 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
s插入vector
并将向量传递到bar
So now in python we can stick Foo
s 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)
这篇关于使用Boost.python将Python列表传递给C ++向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文