简体   繁体   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. I'm trying to bind C++ class static non-arguments method to python class static constant field use pybind11.

Here's my sample code config.cpp :这是我的示例代码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);
}

The config module compiles successfully, but when I use it in python3 console, here's the exception it raise:配置模块编译成功,但是当我在 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'>

How should I fix this?我应该如何解决这个问题?

Or is there a way to bind C++ function to python module constant attributes/variables?或者有没有办法将 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 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

The key is to use C++11 lambda, so update PYBIND11_MODULE part in config.cpp like this:关键是要使用 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(); });
}

For the second question, how to bind C++ non-arguments function to python constant attributes/variables , I still have no idea.对于第二个问题,如何将C++ 非参数 function绑定到python 常量属性/变量,我仍然不知道。

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

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