首页 > 解决方案 > 如何将文档字符串传递给 pybind11::def_property_readonly?

问题描述

我正在尝试将记录在案的只读属性添加到使用 pybind11 定义的 python 扩展中的类中。通常这是通过在定义调用中添加一个字符串参数来完成的。但是,当我将字符串参数添加到只读属性定义调用时,会出现模板编译错误。

编译但没有文档字符串:

[...]
.def_property_readonly(
        "property_name",
        [](){ return ""; })
[...]

有一个文档字符串但不编译:

[...]
.def_property_readonly(
        "property_name",
        [](){ return ""; },
        std::string("docstring"))
[...]

标签: pybind11

解决方案


你必须通过 aconst char *而不是 a std::string

[...]
.def_property_readonly(
        "property_name",
        [](){ return ""; },
        "const char docstring")
[...]

推荐阅读