diff --git a/src/runtime/Util.cs b/src/runtime/Util.cs
index dc5f78608..29a5170ab 100644
--- a/src/runtime/Util.cs
+++ b/src/runtime/Util.cs
@@ -3,7 +3,7 @@
namespace Python.Runtime
{
- internal class Util
+ internal static class Util
{
internal static Int64 ReadCLong(IntPtr tp, int offset)
{
@@ -29,5 +29,12 @@ internal static void WriteCLong(IntPtr type, int offset, Int64 flags)
Marshal.WriteInt64(type, offset, flags);
}
}
+
+ ///
+ /// Null-coalesce: if parameter is not
+ /// , return it. Otherwise return .
+ ///
+ internal static IntPtr Coalesce(this IntPtr primary, IntPtr fallback)
+ => primary == IntPtr.Zero ? fallback : primary;
}
-}
\ No newline at end of file
+}
diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs
index aec2a412e..a2da04af3 100644
--- a/src/runtime/pythonengine.cs
+++ b/src/runtime/pythonengine.cs
@@ -758,11 +758,14 @@ public static void With(PyObject obj, Action Body)
catch (PythonException e)
{
ex = e;
- type = ex.PyType;
- val = ex.PyValue;
- traceBack = ex.PyTB;
+ type = ex.PyType.Coalesce(type);
+ val = ex.PyValue.Coalesce(val);
+ traceBack = ex.PyTB.Coalesce(traceBack);
}
+ Runtime.XIncref(type);
+ Runtime.XIncref(val);
+ Runtime.XIncref(traceBack);
var exitResult = obj.InvokeMethod("__exit__", new PyObject(type), new PyObject(val), new PyObject(traceBack));
if (ex != null && !exitResult.IsTrue()) throw ex;