Skip to content

Commit 8699639

Browse files
committed
pybind11/pytypes.h inc_ref(), dec_ref() PyGILState_Check() **excluding** nullptr
Guarded by `PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF`
1 parent 0176632 commit 8699639

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

include/pybind11/detail/common.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,11 @@
262262
# define PYBIND11_HAS_U8STRING
263263
#endif
264264

265+
#if !defined(NDEBUG) && !defined(PY_ASSERT_GIL_HELD_INCREF_DECREF) \
266+
&& !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
267+
# define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
268+
#endif
269+
265270
// #define PYBIND11_STR_LEGACY_PERMISSIVE
266271
// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
267272
// (probably surprising and never documented, but this was the

include/pybind11/pytypes.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,11 @@ class handle : public detail::object_api<handle> {
246246
const handle &inc_ref() const & {
247247
#ifdef PYBIND11_HANDLE_REF_DEBUG
248248
inc_ref_counter(1);
249+
#endif
250+
#if defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
251+
if (m_ptr != nullptr && !PyGILState_Check()) {
252+
throw std::runtime_error("pybind11::handle::inc_ref() PyGILState_Check() failure.");
253+
}
249254
#endif
250255
Py_XINCREF(m_ptr);
251256
return *this;
@@ -257,6 +262,11 @@ class handle : public detail::object_api<handle> {
257262
this function automatically. Returns a reference to itself.
258263
\endrst */
259264
const handle &dec_ref() const & {
265+
#if defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
266+
if (m_ptr != nullptr && !PyGILState_Check()) {
267+
throw std::runtime_error("pybind11::handle::dec_ref() PyGILState_Check() failure.");
268+
}
269+
#endif
260270
Py_XDECREF(m_ptr);
261271
return *this;
262272
}

0 commit comments

Comments
 (0)