Skip to content

Commit 7d6713a

Browse files
Use weakref to clean up captured function object in def_buffer (#2634)
1 parent 06a5401 commit 7d6713a

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

include/pybind11/pybind11.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1315,7 +1315,8 @@ class class_ : public detail::generic_type {
13151315
return *this;
13161316
}
13171317

1318-
template <typename Func> class_& def_buffer(Func &&func) {
1318+
template <typename Func>
1319+
class_& def_buffer(Func &&func) {
13191320
struct capture { Func func; };
13201321
auto *ptr = new capture { std::forward<Func>(func) };
13211322
install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
@@ -1324,6 +1325,10 @@ class class_ : public detail::generic_type {
13241325
return nullptr;
13251326
return new buffer_info(((capture *) ptr)->func(caster));
13261327
}, ptr);
1328+
weakref(m_ptr, cpp_function([ptr](handle wr) {
1329+
delete ptr;
1330+
wr.dec_ref();
1331+
})).release();
13271332
return *this;
13281333
}
13291334

0 commit comments

Comments
 (0)