【问题标题】:pybind11: how to implement a with context managerpybind11:如何使用上下文管理器实现
【发布时间】:2019-05-30 05:12:37
【问题描述】:

我正在尝试使用 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

它们是更具体的绑定吗,我可以使用吗?

【问题讨论】:

  • 很抱歉撞了一个旧帖子,但您是否设法使用 pybind11 实现了一个 'with' 上下文管理器?我想做类似的事情,但在这个问题上遇到了绑定语法:stackoverflow.com/questions/55452762/…

标签: python c++ with-statement pybind11


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2011-12-25
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多