Skip to content

Commit 0442057

Browse files
committed
prevent crash during debugging when attempting to inspect PyObject without GIL
1 parent 8e1d4db commit 0442057

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

src/runtime/debughelper.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,16 @@ public static void PrintHexBytes(byte[] bytes)
141141
[Conditional("DEBUG")]
142142
public static void EnsureGIL()
143143
{
144-
if (Runtime.PythonVersion >= new Version(3,4)) {
145-
Debug.Assert(Runtime.PyGILState_Check() == 1, "GIL must be acquired");
146-
}
144+
Debug.Assert(HaveInterpreterLock() != false, "GIL must be acquired");
145+
}
146+
147+
public static bool? HaveInterpreterLock()
148+
{
149+
// not supported on older version
150+
if (Runtime.PythonVersion < new Version(3, 4))
151+
return null;
152+
153+
return Runtime.PyGILState_Check() == 1;
147154
}
148155

149156
[Conditional("DEBUG")]

src/runtime/pyobject.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ public interface IPyDisposable : IDisposable
2020
/// PY3: https://docs.python.org/3/c-api/object.html
2121
/// for details.
2222
/// </summary>
23+
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
2324
public class PyObject : DynamicObject, IEnumerable, IPyDisposable
2425
{
2526
#if TRACE_ALLOC
@@ -1085,6 +1086,10 @@ public override string ToString()
10851086
return result;
10861087
}
10871088

1089+
string DebuggerDisplay => DebugUtil.HaveInterpreterLock() != false
1090+
? this.ToString()
1091+
: $"pyobj at 0x{this.obj:X} (get Py.GIL to see more info)";
1092+
10881093

10891094
/// <summary>
10901095
/// Equals Method

0 commit comments

Comments
 (0)