我的目标是修改在中声明的数组C++ struct
并赋予默认值。
我读过了this https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html#making-opaque-types, this https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html#binding-stl-containers,但不幸的是我无法将其与我的问题联系起来。
示例代码
class Math{
struct Data
{
std::array<float, 5> id_ = {0}; // all value set to ZERO
std::array<uint32_t, 5> length_ = {0}; // all value set to ZERO
std::array<bool, 5> status_ = {0}; // all value set to ZERO
float x_ = 7.5;
};
};
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/complex.h>
namespace py = pybind11;
PYBIND11_MODULE(do_math, m)
{
py::class_<Math::Data> Data (m, "Data");
Data.def(py::init<>())
.def_readwrite("id_", &Math::Data::id_)
.def_readwrite("length_", &Math::Data::length_)
.def_readwrite("status_", &Math::Data::status_)
.def_readwrite("x_", &Math::Data::x_);
}
- 现在我想修改所有
std::array
会员价值。我只在这里展示id_
.
- In
python file
我可以访问id_
成员变量及其打印[0.0, 0.0, 0.0, 0.0, 0.0]
以及x_
哪个输出是7.5
import do_math
struct_obj = do_math.Data()
print(struct_obj.id_)
print(struct_obj.x_)
struct_obj.id_[2] = 2.2 # cannot modify
struct_obj.x_ = 1.5 # it is modified
仍然输出struct_obj.id_
is [0.0, 0.0, 0.0, 0.0, 0.0]
while struct_obj.x_
更改为1.5
。我该如何修改id_
python 中的数组?
到目前为止已采取的方法
依照指示这个答案 https://stackoverflow.com/a/58723691/10634362我曾尝试实施但失败了。
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/complex.h>
#include "pybind11/numpy.h"
#include <pybind11/pytypes.h>
namespace py = pybind11;
PYBIND11_MODULE(do_math, m)
{
py::class_<Math::Data> Data (m, "Data", py::buffer_protocol());
Data.def(py::init<>())
.def_property("id_", [](Math::Data &p) -> py::array {
auto dtype = py::dtype(py::format_descriptor<float>::format());
auto base = py::array(dtype, {5}, {sizeof(float)});
return py::array(
dtype, {5}, {sizeof(float)}, p.id_, base);
}, [](Math::Data& p) {});
}
- 错误信息 :
error: no matching constructor for initialization of 'py::array' return py::array(