From 7d6713a46d30f51014632f74c13667d42bfa783a Mon Sep 17 00:00:00 2001 From: Yannick Jadoul Date: Mon, 2 Nov 2020 18:39:40 +0100 Subject: [PATCH] Use weakref to clean up captured function object in def_buffer (#2634) --- include/pybind11/pybind11.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index fa98f7c18..761f2a717 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -1315,7 +1315,8 @@ public: return *this; } - template class_& def_buffer(Func &&func) { + template + class_& def_buffer(Func &&func) { struct capture { Func func; }; auto *ptr = new capture { std::forward(func) }; install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* { @@ -1324,6 +1325,10 @@ public: return nullptr; return new buffer_info(((capture *) ptr)->func(caster)); }, ptr); + weakref(m_ptr, cpp_function([ptr](handle wr) { + delete ptr; + wr.dec_ref(); + })).release(); return *this; }