将 Python 列表传递给 C++使用 Boost.python 进行矢量化
如何将对象类型 ClassName
的 Python 列表传递给接受 vector
的 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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您有一个采用
std::vector
的函数,处理此问题的最简单方法是将
vector
公开给 python。所以现在在Python中我们可以将
Foo
粘贴到向量
中并将向量传递给bar
Assuming you have function that takes a
std::vector<Foo>
The easiest way to handle this is to expose the
vector
to python.So now in python we can stick
Foo
s into avector
and pass the vector tobar
找到了一个可以解决我的问题的迭代器:
Found an iterator that solves my problem: