Skip to content

Commit 9498c07

Browse files
committed
fixed crash in finalizer of CLR types defined in Python, that survive engine shutdown
#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.
1 parent f506d65 commit 9498c07

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
namespace Python.EmbeddingTest
2+
{
3+
using NUnit.Framework;
4+
5+
using Python.Runtime;
6+
7+
public class TestPythonDerivedType
8+
{
9+
[OneTimeSetUp]
10+
public void SetUp()
11+
{
12+
PythonEngine.Initialize();
13+
}
14+
15+
[OneTimeTearDown]
16+
public void Dispose()
17+
{
18+
PythonEngine.Shutdown();
19+
}
20+
21+
// Exception in finalizer of custom encoder
22+
// https://github.com/pythonnet/pythonnet/issues/1256
23+
[Test]
24+
public void TestFinalizer_AfterShutdown()
25+
{
26+
PythonEngine.Exec(@"
27+
import clr
28+
from Python.Runtime import PyObjectConversions
29+
from Python.Runtime.Codecs import RawProxyEncoder
30+
class ListAsRawEncoder(RawProxyEncoder):
31+
__namespace__ = 'Python.Runtime.Codecs'
32+
def CanEncode(self, clr_type):
33+
return clr_type.Name == 'IList`1' and clr_type.Namespace == 'System.Collections.Generic'
34+
35+
list_encoder = ListAsRawEncoder()
36+
PyObjectConversions.RegisterEncoder(list_encoder)
37+
");
38+
PythonEngine.Shutdown();
39+
System.GC.Collect();
40+
System.GC.WaitForPendingFinalizers();
41+
}
42+
}
43+
}

src/runtime/classderived.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -857,7 +857,7 @@ public static void Finalize(IPythonDerivedType obj)
857857
{
858858
if (0 == Runtime.Py_IsInitialized() || Runtime.IsFinalizing)
859859
{
860-
self.gcHandle.Free();
860+
if (self.gcHandle.IsAllocated) self.gcHandle.Free();
861861
return;
862862
}
863863
}
@@ -872,7 +872,7 @@ public static void Finalize(IPythonDerivedType obj)
872872
// If python's been terminated then just free the gchandle.
873873
if (0 == Runtime.Py_IsInitialized() || Runtime.IsFinalizing)
874874
{
875-
self.gcHandle.Free();
875+
if (self.gcHandle.IsAllocated) self.gcHandle.Free();
876876
return;
877877
}
878878

0 commit comments

Comments
 (0)