Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9498c07

Browse files
committed
fixed crash in finalizer of CLR types defined in Python, that survive engine shutdown
#1256During 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 parentf506d65 commit9498c07

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+
namespacePython.EmbeddingTest
2+
{
3+
usingNUnit.Framework;
4+
5+
usingPython.Runtime;
6+
7+
publicclassTestPythonDerivedType
8+
{
9+
[OneTimeSetUp]
10+
publicvoidSetUp()
11+
{
12+
PythonEngine.Initialize();
13+
}
14+
15+
[OneTimeTearDown]
16+
publicvoidDispose()
17+
{
18+
PythonEngine.Shutdown();
19+
}
20+
21+
// Exception in finalizer of custom encoder
22+
// https://github.com/pythonnet/pythonnet/issues/1256
23+
[Test]
24+
publicvoidTestFinalizer_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)

[8]ページ先頭

©2009-2025 Movatter.jp