My goal is to modify array which are declared in C++ struct and assigned with default value.
I have read this, this, but unfortunately I cannot relate it with my problem.
Sample Code
- C++
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;
};
};
- Binded Code
#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_);
}
- Now, I would like to modify all
std::arraymember value. I am only showing hereid_. - In
python fileI can access theid_member variable and it prints[0.0, 0.0, 0.0, 0.0, 0.0]as well as thex_which output is7.5
import do_math
struct_obj = do_math.Data()
print(struct_obj.id_)
print(struct_obj.x_)
- Now would like to modify the value of
id_but here I am unable to do it.
struct_obj.id_[2] = 2.2 # cannot modify
struct_obj.x_ = 1.5 # it is modified
Still output of struct_obj.id_ is [0.0, 0.0, 0.0, 0.0, 0.0] while struct_obj.x_ is changed to 1.5. How can I modify the id_ array in python?
Approach has taken so far
By following this answer I have tried to implement but failed.
#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 Message :
error: no matching constructor for initialization of 'py::array' return py::array(