Skip to content

Commit d10f154

Browse files
committed
Keep PyMethodDef alive through a weakref in Python 3.9
1 parent 61e40f6 commit d10f154

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

include/pybind11/pybind11.h

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,15 @@ class cpp_function : public function {
369369
}
370370

371371
m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
372+
373+
#if PY_VERSION_HEX >= 0x03090000
374+
weakref(m_ptr, cpp_function([rec_capsule](handle wr) {
375+
rec_capsule.dec_ref();
376+
wr.dec_ref();
377+
})).release();
378+
rec_capsule.inc_ref();
379+
#endif
380+
372381
if (!m_ptr)
373382
pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
374383
} else {
@@ -466,7 +475,7 @@ class cpp_function : public function {
466475
}
467476
if (rec->def) {
468477
std::free(const_cast<char *>(rec->def->ml_doc));
469-
//delete rec->def;
478+
delete rec->def;
470479
}
471480
delete rec;
472481
rec = next;

0 commit comments

Comments
 (0)