最后,我可以使用 [] 运算符在 python 中使用 std::vector 。诀窍是在 boost C++ 包装器中简单地提供一个容器来处理内部向量内容:
#include <boost/python.hpp>
#include <vector>
class world
{
std::vector<double> myvec;
void add(double n)
{
this->myvec.push_back(n);
}
std::vector<double> show()
{
return this->myvec;
}
};
BOOST_PYTHON_MODULE(hello)
{
class_<std::vector<double> >("double_vector")
.def(vector_indexing_suite<std::vector<double> >())
;
class_<World>("World")
.def("show", &World::show)
.def("add", &World::add)
;
}
另一个挑战是:如何将 python 列表转换为 std::vectors?我尝试添加一个期望 std::vector 作为参数的 c++ 类,并添加了相应的包装器代码:
#include <boost/python.hpp>
#include <vector>
class world
{
std::vector<double> myvec;
void add(double n)
{
this->myvec.push_back(n);
}
void massadd(std::vector<double> ns)
{
// Append ns to this->myvec
}
std::vector<double> show()
{
return this->myvec;
}
};
BOOST_PYTHON_MODULE(hello)
{
class_<std::vector<double> >("double_vector")
.def(vector_indexing_suite<std::vector<double> >())
;
class_<World>("World")
.def("show", &World::show)
.def("add", &World::add)
.def("massadd", &World::massadd)
;
}
但如果这样做,我最终会得到以下 Boost.Python.ArgumentError:
>>> w.massadd([2.0,3.0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
World.massadd(World, list)
did not match C++ signature:
massadd(World {lvalue}, std::vector<double, std::allocator<double> >)
谁能告诉我如何在我的 c++ 函数中访问 python 列表?
谢谢,丹尼尔