pybind / pybind/pybind11

Modify default value of `std::array`

Open
#4,262 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

triage
Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Required prerequisites
Problem description

Would like to modify an array which is declared in C++ struct and assigned with default value

Reproducible example 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;
};
};
  • I am avoiding whole code which has to bind (considering, module name is do_math)
.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::array member value. i am only showing here id_.
  • In py file I can access the id_ member variable and it prints [0.0, 0.0, 0.0, 0.0, 0.0] as well as the x_ which output is 7.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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the .def_readwrite bindings for the std::array members and trace how the exposed array is read and written from Python. Reproduce the id_[2] assignment alongside the working x_ assignment, then verify that a supported binding behavior allows changes to persist in the C++ object.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.