Reputation: 443
I am given a class with a private variable locked_
. This variable can be accessed via the methods bool& locked();
and bool locked() const;
class Test {
bool& locked();
bool locked() const;
private:
bool locked_{true};
};
I am not allowed to alter class Test
, yet I must write a pybind11 interface that allows both setting and retrieving locked_
.
I cannot use .def_readwrite("locked", &Test::locked_);
since locked_
is of course private.
My attempts using
.def("locked", static_cast<bool& (Test::*)()>(&Test::locked), "locked", py::return_value_policy::reference_internal);
did compile however merely return a bool and not some sort of modifiable reference to bool.
How can I make locked read/write accessible without "touching" the original C++ implementation.
Upvotes: 1
Views: 1400
Reputation: 122830
I still don't know pybind but I am starting to learn from your questions and I remember that def
accepts lambdas. You can wrap the call to the member like this:
auto locker = [](Test& t, bool lock) { t.locked() = lock; };
I am not sure if you need to do something extra to make def
work with your custom Test
, so I suppose it can be used like this:
m.def("locker", locker);
Upvotes: 2