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; }