8000 fixed crash when Python derived class instances survive past early sh… · pythonnet/pythonnet@932fce2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 932fce2

Browse files
committed
fixed crash when Python derived class instances survive past early shutdown
1 parent 85fab3b commit 932fce2

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/runtime/classderived.cs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,19 +69,23 @@ internal ClassDerivedObject(Type tp) : base(tp)
6969

7070
public new static void tp_dealloc(NewReference ob)
7171
{
72-
var self = (CLRObject)GetManagedObject(ob.Borrow())!;
72+
var self = (CLRObject?)GetManagedObject(ob.Borrow());
7373

7474
// don't let the python GC destroy this object
7575
Runtime.PyObject_GC_UnTrack(ob.Borrow());
7676

77-
// The python should now have a ref count of 0, but we don't actually want to
78-
// deallocate the object until the C# object that references it is destroyed.
79-
// So we don't call PyObject_GC_Del here and instead we set the python
80-
// reference to a weak reference so that the C# object can be collected.
81-
GCHandle oldHandle = GetGCHandle(ob.Borrow());
82-
GCHandle gc = GCHandle.Alloc(self, GCHandleType.Weak);
83-
SetGCHandle(ob.Borrow(), gc);
84-
oldHandle.Free();
77+
// self may be null after Shutdown begun
78+
if (self is not null)
79+
{
80+
// The python should now have a ref count of 0, but we don't actually want to
81+
// deallocate the object until the C# object that references it is destroyed.
82+
// So we don't call PyObject_GC_Del here and instead we set the python
83+
// reference to a weak reference so that the C# object can be collected.
84+
GCHandle oldHandle = GetGCHandle(ob.Borrow());
85+
GCHandle gc = GCHandle.Alloc(self, GCHandleType.Weak);
86+
SetGCHandle(ob.Borrow(), gc);
87+
oldHandle.Free();
88+
}
8589
}
8690

8791
/// <summary>

0 commit comments

Comments
 (0)
0