如何传递对象类型的 Python 列表ClassName
到一个接受a的C++函数vector<ClassName>
?
我发现最好的是这样的:example http://mail.python.org/pipermail/cplusplus-sig/2003-September/005367.html。不幸的是,代码崩溃了,我似乎无法弄清楚为什么。这是我使用的:
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
到蟒蛇。
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
并将向量传递给bar
from awesome_module import *
foo_vector = VectorOfFoo()
foo_vector.extend(Foo(arg) for arg in arglist)
bar(foo_vector)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)