fba*_*lic 1 c++ python pointers pybind11
我有定义一个curves类、一个curve类和一个point类的C++ 代码,我正在尝试通过 pybind11 为这些类编写 Python 绑定并在 Python 中使用它们。
这些类的 pybind11 绑定如下所示:
namespace py = pybind11;
PYBIND11_MODULE(mymodule, m) {
py::class_<_point>(m, "_point")
.def(py::init<double, double>())
.def_readwrite("next", &point::next)
.def_readwrite("prev", &point::prev)
.def_readonly("x1", &point::x1)
.def_readonly("x2", &point::x2);
py::class_<curve>(m, "curve")
.def(py::init<point*>()) //constructor 1
.def(py::init()) //constructor 2
.def_readwrite("first", &curve::first)
.def_readwrite("last", &curve::last)
.def_readwrite("next", &curve::next)
.def_readwrite("prev", &curve::prev);
py::class_<curves>(m, "curves")
.def(py::init())
.def_readwrite("first", &curves::first)
.def_readwrite("last", &curves::last);
}
Run Code Online (Sandbox Code Playgroud)
在 C++ 中,我可以通过以下方式遍历一个由curves对象curve
组成的point对象:
for(curve *c=curves_pointer->first; c; c=c->next) {
for(point *p=c->first; p; p=p->next) {
cout << p->x1 << "," <<p->x2 << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
例如,在 Python 中,我可以使用 访问单个点curves_instance.last.first.x1,但我不知道如何遍历所有曲线、点等。
小智 5
我认为正确的答案__iter__是使用pybind11::make_iterator. 此处提供了一个示例。
我认为是py::make_iterator:
.def("__iter__", [](const Sequence &s) { return py::make_iterator(s.begin(), s.end()); },
py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |