Skip to content

Commit

Permalink
Use weakref to clean up captured function object in def_buffer (#2634)
Browse files Browse the repository at this point in the history
  • Loading branch information
YannickJadoul authored Nov 2, 2020
1 parent 06a5401 commit 7d6713a
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -1315,7 +1315,8 @@ class class_ : public detail::generic_type {
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* {
Expand All @@ -1324,6 +1325,10 @@ class class_ : public detail::generic_type {
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;
}

Expand Down

0 comments on commit 7d6713a

Please sign in to comment.