我正在尝试使用 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_type
、exc_value
和traceback
是什么类型。我想它们可以很简单 pybind11::object
?
我可以使用它们更具体的绑定(bind)吗?
最佳答案
事实上,这些参数将作为 Python 对象出现,因此您应该为它们使用 pybind11::object
类型。使用 void*
不是解决方案。
Pybind11 可能是目前使用 C++ 作为其语言的 C++ 机制的最佳 Python 包装器。
关于python - pybind11:如何使用上下文管理器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025245/