Skip to content

fix: PyCapsule_GetDestructor is allowed to return a nullptr destructor #4221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -1829,18 +1829,18 @@ class capsule : public object {
// guard if destructor called while err indicator is set
error_scope error_guard;
auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
if (destructor == nullptr) {
if (PyErr_Occurred()) {
throw error_already_set();
}
pybind11_fail("Unable to get capsule context");
if (PyErr_Occurred()) {
throw error_already_set();
}
const char *name = get_name_in_error_scope(o);
void *ptr = PyCapsule_GetPointer(o, name);
if (ptr == nullptr) {
throw error_already_set();
}
destructor(ptr);

if (destructor != nullptr) {
destructor(ptr);
}
});

if (!m_ptr || PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) {
Expand Down
6 changes: 6 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,12 @@ TEST_SUBMODULE(pytypes, m) {
return capsule;
});

m.def("return_capsule_with_explicit_nullptr_dtor", []() {
py::print("creating capsule with explicit nullptr dtor");
return py::capsule(reinterpret_cast<void *>(1234),
static_cast<void (*)(void *)>(nullptr)); // PR #4221
});

// test_accessors
m.def("accessor_api", [](const py::object &o) {
auto d = py::dict();
Expand Down
11 changes: 11 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,17 @@ def test_capsule(capture):
"""
)

with capture:
a = m.return_capsule_with_explicit_nullptr_dtor()
del a
pytest.gc_collect()
assert (
capture.unordered
== """
creating capsule with explicit nullptr dtor
"""
)


def test_accessors():
class SubTestObject:
Expand Down