簡體   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