【发布时间】:2023-04-08 06:56:01
【问题描述】:
我有一个用PyBind11 包裹的c++ 类。问题是:当Python 脚本结束时,c++ destructor 不会被自动调用。这会导致退出混乱,因为网络资源需要由析构函数释放。
作为一种变通方法,有必要明确删除Python 对象,但我不明白为什么!
请有人解释这里出了什么问题以及如何在Python 对象被垃圾收集时自动调用destructor?
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
【问题讨论】:
标签: python c++ destructor pybind11