Use weakref to clean up captured function object in def_buffer (#2634)

This commit is contained in:
Yannick Jadoul 2020-11-02 18:39:40 +01:00 committed by GitHub
parent 06a54018c8
commit 7d6713a46d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1315,7 +1315,8 @@ public:
return *this;
}
template <typename Func> class_& def_buffer(Func &&func) {
template <typename Func>
class_& def_buffer(Func &&func) {
struct capture { Func func; };
auto *ptr = new capture { std::forward<Func>(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;
}