55using System . Linq ;
66using System . Reflection ;
77using System . Reflection . Emit ;
8+ using System . Runtime . CompilerServices ;
89using System . Runtime . InteropServices ;
910
1011using Python . Runtime . Native ;
@@ -34,6 +35,21 @@ internal class ClassDerivedObject : ClassObject
3435 private static Dictionary < string , AssemblyBuilder > assemblyBuilders ;
3536 private static Dictionary < Tuple < string , string > , ModuleBuilder > moduleBuilders ;
3637
38+ /// <summary>
39+ /// Python objects whose .NET object holds one reference to them, taken in <see cref="tp_finalize"/>
40+ /// </summary>
41+ internal static readonly HashSet < IntPtr > KeptByManagedObject = new ( ) ;
42+ /// <summary>
43+ /// Python objects whose .NET object was finalized while it held a reference to them:
44+ /// <see cref="tp_dealloc"/> frees them
45+ /// </summary>
46+ internal static readonly HashSet < IntPtr > ReleasedByManagedObject = new ( ) ;
47+ /// <summary>
48+ /// Nothing else references the wrapper of a .NET object its Python object holds weakly:
49+ /// this keeps it alive as long as the .NET object
50+ /// </summary>
51+ private static readonly ConditionalWeakTable < object , CLRObject > WeaklyHeldWrappers = new ( ) ;
52+
3753 static ClassDerivedObject ( )
3854 {
3955 assemblyBuilders = new Dictionary < string , AssemblyBuilder > ( ) ;
@@ -44,6 +60,9 @@ public static void Reset()
4460 {
4561 assemblyBuilders = new Dictionary < string , AssemblyBuilder > ( ) ;
4662 moduleBuilders = new Dictionary < Tuple < string , string > , ModuleBuilder > ( ) ;
63+ KeptByManagedObject . Clear ( ) ;
64+ ReleasedByManagedObject . Clear ( ) ;
65+ WeaklyHeldWrappers . Clear ( ) ;
4766 }
4867
4968 internal ClassDerivedObject ( Type tp ) : base ( tp )
@@ -76,20 +95,79 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo
7695 // don't let the python GC destroy this object
7796 Runtime . PyObject_GC_UnTrack ( ob . Borrow ( ) ) ;
7897
98+ if ( ReleasedByManagedObject . Remove ( ob . DangerousGetAddress ( ) ) )
99+ {
100+ PythonDerivedType . Finalize ( ob . DangerousMoveToPointer ( ) ) ;
101+ return ;
102+ }
103+
79104 // self may be null after Shutdown begun
80105 if ( self is not null )
81106 {
82107 // The python should now have a ref count of 0, but we don't actually want to
83108 // deallocate the object until the C# object that references it is destroyed.
84109 // So we don't call PyObject_GC_Del here and instead we set the python
85110 // reference to a weak reference so that the C# object can be collected.
86- GCHandle oldHandle = GetGCHandle ( ob . Borrow ( ) ) ;
87- GCHandle gc = GCHandle . Alloc ( self , GCHandleType . Weak ) ;
88- SetGCHandle ( ob . Borrow ( ) , gc ) ;
89- oldHandle . Free ( ) ;
111+ ReplaceGCHandle ( ob . Borrow ( ) , self , GCHandleType . Weak ) ;
90112 }
91113 }
92114
115+ /// <summary>
116+ /// Called by the Python cyclic GC on an object it found unreachable from Python, before it clears
117+ /// the cycle. .NET may still reference the object, which Python can't see, so instead of letting
118+ /// the cycle be cleared, the .NET object keeps one reference to the Python object, and the Python
119+ /// object stops keeping the .NET object alive, as <see cref="tp_dealloc"/> does. Python gets that
120+ /// reference back in <see cref="ToPython"/>, and the .NET object releases it when it's finalized.
121+ /// </summary>
122+ public static void tp_finalize ( BorrowedReference ob )
123+ {
124+ // The GC marks an object finalized before it calls tp_finalize and doesn't call it again
125+ // once marked. Otherwise, it's a direct __del__ call from Python, which still references the object.
126+ if ( ( GCPrev ( ob ) & FinalizedFlag ) == 0 )
127+ {
128+ return ;
129+ }
130+
131+ var self = ( CLRObject ? ) GetManagedObject ( ob ) ;
132+ // null once the .NET object is gone: the GC frees the cycle
133+ if ( self is null )
134+ {
135+ return ;
136+ }
137+
138+ // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again
139+ GCPrev ( ob ) & = ~ FinalizedFlag ;
140+ Runtime . XIncref ( ob ) ;
141+ KeptByManagedObject . Add ( ob . DangerousGetAddress ( ) ) ;
142+ ReplaceGCHandle ( ob , self , GCHandleType . Weak ) ;
143+ }
144+
145+ /// <summary>
146+ /// _PyGC_PREV_MASK_FINALIZED: the GC's finalized flag in _gc_prev
147+ /// </summary>
148+ private const nint FinalizedFlag = 1 ;
149+
150+ /// <summary>
151+ /// _gc_prev, the last field of the GC header that precedes the object
152+ /// </summary>
153+ private static unsafe ref nint GCPrev ( BorrowedReference ob )
154+ => ref * ( ( nint * ) ob . DangerousGetAddress ( ) - 1 ) ;
155+
156+ private static void ReplaceGCHandle ( BorrowedReference ob , CLRObject self , GCHandleType type )
157+ {
158+ if ( type == GCHandleType . Weak )
159+ {
160+ WeaklyHeldWrappers . AddOrUpdate ( self . inst , self ) ;
161+ }
162+ else
163+ {
164+ WeaklyHeldWrappers . Remove ( self . inst ) ;
165+ }
166+ GCHandle oldHandle = GetGCHandle ( ob ) ;
167+ SetGCHandle ( ob , GCHandle . Alloc ( self , type ) ) ;
168+ oldHandle . Free ( ) ;
169+ }
170+
93171 /// <summary>
94172 /// No-op clear. Real cleanup happens in <seealso cref="Finalize(IntPtr)"/>
95173 /// </summary>
@@ -113,6 +191,13 @@ internal static NewReference ToPython(IPythonDerivedType obj)
113191 return default ;
114192 }
115193
194+ if ( KeptByManagedObject . Remove ( self . DangerousGetAddress ( ) ) )
195+ {
196+ // Python takes over the reference the .NET object kept in tp_finalize
197+ ReplaceGCHandle ( self , ( CLRObject ) GetManagedObject ( self ) ! , GCHandleType . Normal ) ;
198+ return NewReference . DangerousFromPointer ( self . DangerousGetAddress ( ) ) ;
199+ }
200+
116201 var result = new NewReference ( self ) ;
117202
118203 // when the C# constructor creates the python object it starts as a weak
@@ -123,11 +208,7 @@ internal static NewReference ToPython(IPythonDerivedType obj)
123208 if ( Runtime . Refcount ( self ) == 1 )
124209 {
125210 Runtime . _Py_NewReference ( self ) ;
126- GCHandle weak = GetGCHandle ( self ) ;
127- var clrObject = GetManagedObject ( self ) ;
128- GCHandle gc = GCHandle . Alloc ( clrObject , GCHandleType . Normal ) ;
129- SetGCHandle ( self , gc ) ;
130- weak . Free ( ) ;
211+ ReplaceGCHandle ( self , ( CLRObject ) GetManagedObject ( self ) ! , GCHandleType . Normal ) ;
131212
132213 // now the object has a python reference it's safe for the python GC to track it
133214 Runtime . PyObject_GC_Track ( self ) ;
@@ -933,6 +1014,14 @@ public static void PyFinalize(IPythonDerivedType obj)
9331014
9341015 internal static void Finalize ( IntPtr derived )
9351016 {
1017+ if ( ClassDerivedObject . KeptByManagedObject . Remove ( derived ) )
1018+ {
1019+ // the Python object may still be part of a cycle: Python frees it once nothing references it
1020+ ClassDerivedObject . ReleasedByManagedObject . Add ( derived ) ;
1021+ Runtime . XDecref ( StolenReference . DangerousFromPointer ( derived ) ) ;
1022+ return ;
1023+ }
1024+
9361025 var @ref = NewReference . DangerousFromPointer ( derived ) ;
9371026
9381027 ClassBase . tp_clear ( @ref . Borrow ( ) ) ;
0 commit comments