python - pybind11:如何使用上下文管理器实现

标签 python c++ with-statement pybind11

我正在尝试使用 pybind11 实现带有上下文管理器的 Python。

正在关注 Python's documentation ,我的第一个版本是:

    py::class_<MyResource> (module, "CustomResource", "A custom ressource")
    .def("__enter__", [&] (MyResource& r) { r.lock(); }
        , "Enter the runtime context related to this object")
    .def("__exit__", [&] (MyResource& r, void* exc_type, void* exc_value, void* traceback) { r.unlock(); }
        , "Exit the runtime context related to this object")
    ;

我不知道exc_typeexc_valuetraceback是什么类型。我想它们可以很简单 pybind11::object

我可以使用它们更具体的绑定(bind)吗?

最佳答案

事实上,这些参数将作为 Python 对象出现,因此您应该为它们使用 pybind11::object 类型。使用 void* 不是解决方案。

Pybind11 可能是目前使用 C++ 作为其语言的 C++ 机制的最佳 Python 包装器。

关于python - pybind11:如何使用上下文管理器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025245/

相关文章:

c++ - 从 txt 文件中读取并删除第一行(或最后一行)而不复制

c++ - 当我传递从 stringstream 构建的 char 指针时,ofstream open(...) 失败

javascript - 为什么 eval 不能访问 with 语句下的作用域变量?

python - remote_api_shell.py 与本地主机 dev_appserver

c++ - PythonQt 的智能指针

c++ - 实例化基于 Qt 文件的记录器以在 C++ 库中进行调试

struct - 相当于 with(from Pascal) 到 C/C++

vba - UDF 在任何地方都返回相同的值

python - Django:如何使用ForeignKey字段创建表单(输入为CharField)

Python 正则表达式 : password must contain at least one uppercase letter and number