【问题标题】:pybind11 py::class_.def_property_readonly_static incompatible function arguments for () -> strpybind11 py::class_.def_property_readonly_static () -> str 的函数参数不兼容
【发布时间】:2022-01-26 22:17:25
【问题描述】:

我正在尝试将 C++ 类静态非参数方法绑定到 python 类静态常量字段使用 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);
}

config 模块编译成功,但是当我在 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++ 函数绑定到 python 模块常量属性/变量?

【问题讨论】:

    标签: python c++ static-methods pybind11


    【解决方案1】:

    这是关于如何使用def_property_readonly_static API 将 C++ 类静态非参数方法 绑定到 python 类静态常量属性/变量 的答案:https://pybind11.readthedocs.io/en/stable/advanced/classes.html#static-properties p>

    关键是使用 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++无参函数如何绑定到python常量属性/变量,我还是不知道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-09
      • 2011-06-19
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      相关资源
      最近更新 更多