我有一个
c++
课程,里面有 PyBind11
。问题是:当 Python
脚本结束时,c++
destructor
不会被自动调用。这会导致不整齐的退出,因为网络资源需要由析构函数释放。
作为解决方法,有必要显式删除
Python
对象,但我不明白为什么!
请有人解释一下这里出了什么问题,以及如何在
destructor
对象被垃圾收集时自动调用 Python
?
Pybind11绑定代码:
py::class_<pcs::Listener>(m, "listener")
.def(py::init<const py::object &, const std::string &, const std::string &, const std::string &, const std::string &, const std::set<std::string> &, const std::string & , const bool & , const bool & >(), R"pbdoc(
Monitors network traffic.
When a desired data source is detected a client instance is connected to consume the data stream.
Reconstructs data on receipt, like a jigsaw. Makes requests to fill any gaps. Verifies the data as sequential.
Data is output by callback to Python. Using the method specified in the constructor, which must accept a string argument.
)pbdoc");
在Python中:
#Function to callback
def print_string(str):
print("Python; " + str)
lstnr = listener(print_string, 'tcp://127.0.0.1:9001', clientCertPath, serverCertPath, proxyCertPath, desiredSources, 'time_series_data', enableCurve, enableVerbose)
#Run for a minute
cnt = 0
while cnt < 60:
cnt += 1
time.sleep(1)
#Need to call the destructor explicity for some reason
del lstnr
几年后,我通过在我的 PyBind11 代码中添加
with
和 __enter__
方法处理来启用 Python 上下文管理器
__exit__
支持来解决这个问题:
py::class_<pcs::Listener>(m, "listener")
.def(py::init<const py::object &, const std::string &, const std::string &, const std::string &, const std::string &, const std::set<std::string> &, const std::string & , const bool & , const bool & >(), R"pbdoc(
Monitors network traffic.
When a desired data source is detected a client instance is connected to consume the data stream.
Specify 'type' as 'string' or 'market_data' to facilitate appropriate handling of BarData or string messages.
Reconstructs data on receipt, like a jigsaw. Makes requests to fill any gaps. Verifies the data as sequential.
Data is output by callback to Python. Using the method specified in the constructor, which must accept a string argument.
)pbdoc")
.def("__enter__", &pcs::Listener::enter, R"pbdoc(
Python 'with' context manager support.
)pbdoc")
.def("__exit__", &pcs::Listener::exit, R"pbdoc(
Python 'with' context manager support.
)pbdoc");
在C++类中添加了相应的函数,如下所示:
//For Python 'with' context manager
auto enter(){std::cout << "Context Manager: Enter" << std::endl; return py::cast(this); }//returns a pointer to this object for 'with'....'as' python functionality
auto exit(py::handle type, py::handle value, py::handle traceback){ std::cout << "Context Manager: Exit: " << type << " " << value << " " << traceback << std::endl; }
注意
从
enter()
返回的指针值对于 as
....with
语句中的 as
功能很重要。
传递给
exit(py::handle type, py::handle value, py::handle traceback)
的参数是有用的调试信息。
Python 用法:
with listener(cb, endpoint, clientCertPath, serverCertPath, proxyCertPath, desiredSources, type, enableCurve, enableVerbose):
cnt = 0
while cnt < 10:
cnt += 1
time.sleep(1)
Python 上下文管理器现在调用 C++ 对象上的
pcs::Listener::exit
,这应该释放网络资源。
正如评论中提到的,这种行为的直接原因是 Python 垃圾收集器:当对象的引用计数器为零时,垃圾收集器可能会销毁该对象(从而调用 C++ 析构函数),但它在那一刻不必这样做。
这个想法在此处的答案中得到了更全面的阐述:
https://stackoverflow.com/a/38238013/790979
正如上面链接中提到的,如果您需要在 Python 中的对象生命周期结束时进行清理,一个不错的解决方案是上下文管理,您可以在其中定义
__enter__
和 __exit__
对象的包装器(在 pybind11 中或在 Python 本身中),让 __exit__
释放网络资源,然后在 Python 客户端代码中,类似于:
with listener(print_string, 'tcp://127.0.0.1:9001', clientCertPath, serverCertPath, proxyCertPath, desiredSources, 'time_series_data', enableCurve, enableVerbose) as lstnr:
# Run for a minute
cnt = 0
while cnt < 60:
cnt += 1
time.sleep(1)
GoFaster 的上述解决方案很有帮助,也是正确的方法,但我只是想澄清并纠正他们的主张
Python 上下文管理器现在调用 C++ 对象上的析构函数,从而顺利释放网络资源
这根本不是真的。上下文管理器仅保证
__exit__
将被调用,而不保证任何析构函数将被调用。让我演示一下 - 这是用 C++ 实现的托管资源:
class ManagedResource
{
public:
ManagedResource(int i) : pi(std::make_unique<int>(i))
{
py::print("ManagedResource ctor");
}
~ManagedResource()
{
py::print("ManagedResource dtor");
}
int get() const { return *pi; }
py::object enter()
{
py::print("entered context manager");
return py::cast(this);
}
void exit(py::handle type, py::handle value, py::handle traceback)
{
// release resources
// pi.reset();
py::print("exited context manager");
}
private:
std::unique_ptr<int> pi;
};
Python 绑定:
py::class_<ManagedResource>(m, "ManagedResource")
.def(py::init<int>())
.def("get", &ManagedResource::get)
.def("__enter__", &ManagedResource::enter, R"""(
Enter context manager.
)""")
.def("__exit__", &ManagedResource::exit, R"""(
Leave context manager.
)""");
和一些Python测试代码(请注意,上面的代码还没有释放
__exit__
中的资源):
def f():
with ManagedResource(42) as resource1:
print(f"get = {resource1.get()}")
print(f"hey look I'm still here {resource1.get()}") # not destroyed
if __name__ == "__main__":
f()
print("end")
产生:
ManagedResource ctor
entered context manager
get = 42
exited context manager
hey look I'm still here 42
ManagedResource dtor
end
因此资源被构造,获取内存,并在上下文管理器中访问。到目前为止一切都很好。然而,内存仍然可以在上下文管理器之外访问(并且在调用析构函数之前,这是由 python 运行时决定的,并且超出我们的控制范围,除非我们使用
del
强制它,这完全违背了上下文管理器的目的。
但是我们并没有真正释放
__exit__
中的资源。如果您在该函数中取消注释 pi.reset()
,您将得到以下结果:
ManagedResource ctor
entered context manager
get = 42
exited context manager
Segmentation fault (core dumped)
这次,当你在上下文管理器之外调用
get()
时,ManagedResource
对象本身仍然没有被破坏,但是它里面的资源已经被释放了,
还有更大的危险:如果您在
ManagedResource
块之外创建 with
,您将泄漏资源,因为 __exit__
永远不会被调用。要解决此问题,您需要将从构造函数获取资源推迟到 __enter__
方法,并检查 get
中是否存在资源。
简而言之,这个故事的寓意是:
__enter__
方法中获取,而不是在构造函数中
__exit__
方法中释放,而不是析构函数