当将C++与pybind11
绑定时,我遇到了一个问题,涉及两个返回(const或non—const)引用的类成员;考虑以下代码段:
struct Data {
double value1;
double value2;
};
class Element {
public:
Element() = default;
Element(Data values) : data(values) { }
Element(const Element& other) : data(other.data) { printf("copying from %p\n", &other); }
Data data;
};
class Container {
public:
Container() : data(10, Element(Data{0.1, 0.2})) {};
Element& operator[](size_t idx) { return data[idx]; }
const Element& operator[](size_t idx) const { return data[idx]; }
protected:
std::vector< Element > data;
};
它被绑定到一个Python模块,其中包含:
py::class_< Data > (module, "Data")
.def(py::init< double, double >(), "Constructs a new instance", "v1"_a, "v2"_a)
.def_readwrite("value1", &Data::value1)
.def_readwrite("value2", &Data::value2);
py::class_< Element > (module, "Element")
.def(py::init< Data >(), "Constructs a new instance", "values"_a)
.def_readwrite("data", &Element::data)
.def("__repr__", [](const Element& e){ return std::to_string(e.data.value1); });
py::class_< Container > (module, "Container")
.def(py::init< >(), "Constructs a new instance")
.def("__getitem__", [](Container& c, size_t idx) { return c[idx]; }, "idx"_a)
.def("__setitem__", [](Container& c, size_t idx, Element e) { c[idx] = e; }, "idx"_a, "val"_a);
我在让[]
接线员在Container
班工作时遇到了麻烦
print("-------------")
foo = module.Data(0.9, 0.8)
print(foo.value2)
foo.value2 = 0.7 # works
print(foo.value2)
print("-------------")
e = module.Element(motion.Data(0.3, 0.2))
print(e.data.value1)
e.data.value2 = 0.6 # works
print(e.data.value2)
e.data = foo # works
print(e.data.value2)
print("-------------")
c = motion.Container()
print(c[0].data.value1)
c[0] = e # works
print(c[0].data.value1)
c[0].data = foo # does not work (!)
print(c[0].data.value1)
c[0].data.value1 = 0.0 # does not work (!)
print(c[0].data.value1)
虽然__getitem__
([]
)函数看起来确实像预期的那样工作,但在访问返回对象上的成员时似乎失败了;相反,从返回的引用创建临时副本,并且不应用对该实例的任何更改.
我try 了1)在绑定Element
类时声明std::shared_ptr<Element>
持有者类型;2)在__getitem__
上定义特定的返回值策略py::return_value_policy::reference
和py::return_value_policy::reference_internal
;以及3)定义特定的调用策略py::keep_alive<0,1>()
和py::keep_alive<1,0>()
;但这些解决方案都不起作用.
有什么建议如何解决这个问题吗?