我正在尝试使用 boost python 来创建一个数组
#include <boost/python.hpp>
#include <memory>
#include <vector>
class MyObject
{
public:
MyObject(int value)
: value_(value)
{
}
int value() const { return value_; }
void set_value(int value) { value_ = value; }
private:
int value_;
};
class MyArray
{
public:
MyArray(int size)
: array_(size)
{
for (auto& obj : array_)
{
obj = std::make_shared<MyObject>(0);
}
}
std::shared_ptr<MyObject>& operator[](int index) { return array_[index]; }
int size() const { return static_cast<int>(array_.size()); }
private:
std::vector<std::shared_ptr<MyObject>> array_;
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<MyObject, std::shared_ptr<MyObject>>("MyObject", python::init<int>())
.add_property("value", &MyObject::value, &MyObject::set_value);
python::class_<MyArray, std::shared_ptr<MyArray>>("MyArray", python::init<int>())
.def("__getitem__", &MyArray::operator[], boost::python::return_value_policy<boost::python::copy_non_const_reference>())
.def("__len__", &MyArray::size);
}
它在 Python 中工作得相当好:len 函数工作,访问器 [] 工作得很好,但是 for 循环不会在正确的迭代器处停止,我得到一个 C++ 运行时错误,试图访问 myArray[3],第四个(不存在的)项目
my_array = analyse_script.MyArray(3)
my_array[0].value = 1
my_array[1].value = 2
my_array[2].value = 3
print(len(my_array)) # prints "3"
for obj in my_array:
print(obj.value) # prints "1", "2", "3"
我应该改变什么才能让它发挥作用? 提前致谢!
最后,同事建议我使用 vector_indexing_suite,而不是使用不必要的类 MyArray
所以我的代码看起来像这样并且有效
boost::python::class_<std::vector<std::shared_ptr<MyObject>>>("MyArray")
.def(boost::python::vector_indexing_suite<std::vector<std::shared_ptr<MyObject>>>())
.def("__iter__", boost::python::iterator<std::vector<std::shared_ptr<MyObject>>>())
;
我仍然有兴趣了解为什么我的第一次尝试没有成功,但这不那么紧急!