繁体   English   中英

pybind11 py::class_.def_property_readonly_static 不兼容 function arguments for () -> str

[英]pybind11 py::class_.def_property_readonly_static incompatible function arguments for () -> str

I'm trying to bind C++ class static non-arguments method to python class static constant field use pybind11.

这是我的示例代码config.cpp


namespace py = pybind11;

struct Env {
  static std::string env() {
    return std::getenv("MY_ENV");
  }
};

PYBIND11_MODULE(config, m) {
  m.doc() = "my config module written in C++";
  py::class_<Env>(m, "Env")
    .def_property_readonly_static("ENV", &Env::env);
}

配置模块编译成功,但是当我在 python3 控制台中使用它时,它引发的异常如下:

>>> from config import Env
>>> Env.ENV
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: (): incompatible function arguments. The following argument types are supported:
    1. () -> str

Invoked with: <class 'config.Env'>

我应该如何解决这个问题?

或者有没有办法将 C++ function 绑定到 python 模块常量属性/变量?

Here's the answer about how to bind C++ class static non-arguments method to python class static constant attribute/variable with def_property_readonly_static API: https://pybind11.readthedocs.io/en/stable/advanced/classes.html#static-properties

关键是要使用 C++11 lambda,所以像这样更新config.cpp中的 PYBIND11_MODULE 部分:


PYBIND11_MODULE(config, m) {
  m.doc() = "my config module written in C++";
  py::class_<Env>(m, "Env")
    .def_property_readonly_static("ENV", [](py::object /* self */){ return Env::env(); });
}

对于第二个问题,如何将C++ 非参数 function绑定到python 常量属性/变量,我仍然不知道。

暂无
暂无

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

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