From 1fd6dc2ff785eda31e1762453106e46efbfec747 Mon Sep 17 00:00:00 2001 From: Victor Milovanov Date: Tue, 13 Oct 2020 10:26:42 -0700 Subject: [PATCH] fixed crash in finalizer of CLR types defined in Python, that survive engine shutdown https://github.com/pythonnet/pythonnet/issues/1256 #1256 During engine shutdown all links from Python to .NET instances are severed. If an instance of CLR class defined in Python survives the shutdown (for example, a reference is stored in static field) and later gets finalized, it will attempt to severe link again, which is an invalid operation. The fix is to check if the link has already been severed and skip that step during finalization. --- src/runtime/classderived.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/runtime/classderived.cs b/src/runtime/classderived.cs index e55e89240..7de34420f 100644 --- a/src/runtime/classderived.cs +++ b/src/runtime/classderived.cs @@ -857,7 +857,7 @@ public static void Finalize(IPythonDerivedType obj) { if (0 == Runtime.Py_IsInitialized() || Runtime.IsFinalizing) { - self.gcHandle.Free(); + if (self.gcHandle.IsAllocated) self.gcHandle.Free(); return; } } @@ -872,7 +872,7 @@ public static void Finalize(IPythonDerivedType obj) // If python's been terminated then just free the gchandle. if (0 == Runtime.Py_IsInitialized() || Runtime.IsFinalizing) { - self.gcHandle.Free(); + if (self.gcHandle.IsAllocated) self.gcHandle.Free(); return; }