简体   繁体   English

pybind11 通过引用访问私有 class 成员

[英]pybind11 access private class member via reference

I am given a class with a private variable locked_ .我得到了一个带有私有变量 locked_ 的locked_ This variable can be accessed via the methods bool& locked();这个变量可以通过bool& locked();方法访问。 and bool locked() const;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_ .我不允许更改 class Test ,但我必须编写一个 pybind11 接口,允许设置和检索locked_

I cannot use .def_readwrite("locked", &Test::locked_);我不能使用.def_readwrite("locked", &Test::locked_); since locked_ is of course private.因为locked_当然是私有的。 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.如何在不“接触”原始 C++ 实现的情况下使锁定的读/写可访问。

I still don't know pybind but I am starting to learn from your questions and I remember that def accepts lambdas.我仍然不知道 pybind,但我开始从你的问题中学习,我记得def接受 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:我不确定您是否需要做一些额外的事情来使def与您的自定义Test一起工作,所以我想它可以像这样使用:

m.def("locker", locker);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM