Skip to content

Commit 65374c8

Browse files
authored
pybind11::handle inc_ref() & dec_ref() PyGILState_Check() **excluding** nullptr (#4246)
* pybind11/pytypes.h `inc_ref()`, `dec_ref()` `PyGILState_Check()` **excluding** `nullptr` Guarded by `PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF` * Disable `PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF` for PyPy under Windows. * Add reference to PR #4268 (PyPy Windows)
1 parent 65cc9d2 commit 65374c8

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

include/pybind11/detail/common.h

+9
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,15 @@ PYBIND11_WARNING_POP
323323
# define PYBIND11_HAS_U8STRING
324324
#endif
325325

326+
// See description of PR #4246:
327+
#if !defined(NDEBUG) && !defined(PY_ASSERT_GIL_HELD_INCREF_DECREF) \
328+
&& !(defined(PYPY_VERSION) \
329+
&& defined(_MSC_VER)) /* PyPy Windows: pytest hangs indefinitely at the end of the \
330+
process (see PR #4268) */ \
331+
&& !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
332+
# define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
333+
#endif
334+
326335
// #define PYBIND11_STR_LEGACY_PERMISSIVE
327336
// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
328337
// (probably surprising and never documented, but this was the

include/pybind11/pytypes.h

+10
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,11 @@ class handle : public detail::object_api<handle> {
249249
const handle &inc_ref() const & {
250250
#ifdef PYBIND11_HANDLE_REF_DEBUG
251251
inc_ref_counter(1);
252+
#endif
253+
#if defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
254+
if (m_ptr != nullptr && !PyGILState_Check()) {
255+
throw std::runtime_error("pybind11::handle::inc_ref() PyGILState_Check() failure.");
256+
}
252257
#endif
253258
Py_XINCREF(m_ptr);
254259
return *this;
@@ -260,6 +265,11 @@ class handle : public detail::object_api<handle> {
260265
this function automatically. Returns a reference to itself.
261266
\endrst */
262267
const handle &dec_ref() const & {
268+
#if defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
269+
if (m_ptr != nullptr && !PyGILState_Check()) {
270+
throw std::runtime_error("pybind11::handle::dec_ref() PyGILState_Check() failure.");
271+
}
272+
#endif
263273
Py_XDECREF(m_ptr);
264274
return *this;
265275
}

0 commit comments

Comments
 (0)