@@ -45,6 +45,10 @@ internal class ClassDerivedObject : ClassObject
4545 /// </summary>
4646 internal static readonly HashSet < IntPtr > ReleasedByManagedObject = new ( ) ;
4747 /// <summary>
48+ /// Python objects .NET let go of while Python still referenced them, see <see cref="ReturnToPython"/>
49+ /// </summary>
50+ private static readonly HashSet < IntPtr > ReturnedToPython = new ( ) ;
51+ /// <summary>
4852 /// Nothing else references the wrapper of a .NET object its Python object holds weakly:
4953 /// this keeps it alive as long as the .NET object
5054 /// </summary>
@@ -62,7 +66,9 @@ public static void Reset()
6266 moduleBuilders = new Dictionary < Tuple < string , string > , ModuleBuilder > ( ) ;
6367 KeptByManagedObject . Clear ( ) ;
6468 ReleasedByManagedObject . Clear ( ) ;
69+ ReturnedToPython . Clear ( ) ;
6570 WeaklyHeldWrappers . Clear ( ) ;
71+ finalizedFlagOffset = GetFinalizedFlagOffset ( ) ;
6672 }
6773
6874 internal ClassDerivedObject ( Type tp ) : base ( tp )
@@ -94,6 +100,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo
94100
95101 // don't let the python GC destroy this object
96102 Runtime . PyObject_GC_UnTrack ( ob . Borrow ( ) ) ;
103+ ReturnedToPython . Remove ( ob . DangerousGetAddress ( ) ) ;
97104
98105 if ( ReleasedByManagedObject . Remove ( ob . DangerousGetAddress ( ) ) )
99106 {
@@ -123,7 +130,13 @@ public static void tp_finalize(BorrowedReference ob)
123130 {
124131 // The GC marks an object finalized before it calls tp_finalize and doesn't call it again
125132 // once marked. Otherwise, it's a direct __del__ call from Python, which still references the object.
126- if ( ( GCPrev ( ob ) & FinalizedFlag ) == 0 )
133+ if ( ( FinalizedFlagWord ( ob ) & FinalizedFlag ) == 0 )
134+ {
135+ return ;
136+ }
137+
138+ // .NET already let go of the object while Python still referenced it: the GC frees the cycle
139+ if ( ReturnedToPython . Remove ( ob . DangerousGetAddress ( ) ) )
127140 {
128141 return ;
129142 }
@@ -136,26 +149,70 @@ public static void tp_finalize(BorrowedReference ob)
136149 }
137150
138151 // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again
139- GCPrev ( ob ) & = ~ FinalizedFlag ;
152+ FinalizedFlagWord ( ob ) & = ~ FinalizedFlag ;
140153 Runtime . XIncref ( ob ) ;
141154 KeptByManagedObject . Add ( ob . DangerousGetAddress ( ) ) ;
142- ReplaceGCHandle ( ob , self , GCHandleType . Weak ) ;
155+ // Another object's __del__ may give Python the object back before the cycle is cleared.
156+ // Tracking resurrection keeps the handle valid until Finalize(IntPtr, object) takes the
157+ // .NET object back after its finalizer ran.
158+ ReplaceGCHandle ( ob , self , GCHandleType . WeakTrackResurrection ) ;
159+ }
160+
161+ /// <summary>
162+ /// Called when the .NET object kept the Python object since <see cref="tp_finalize"/> and was
163+ /// finalized while Python still references the Python object: through the cycle, or because Python
164+ /// got the object back without .NET. The Python object keeps the .NET object alive again, as for
165+ /// any object Python holds, and the next time the GC finds the cycle unreachable, it frees it.
166+ /// </summary>
167+ internal static void ReturnToPython ( BorrowedReference ob , object managed )
168+ {
169+ if ( WeaklyHeldWrappers . TryGetValue ( managed , out var self ) )
170+ {
171+ ReplaceGCHandle ( ob , self , GCHandleType . Normal ) ;
172+ GC . ReRegisterForFinalize ( managed ) ;
173+ ReturnedToPython . Add ( ob . DangerousGetAddress ( ) ) ;
174+ }
143175 }
144176
145177 /// <summary>
146- /// _PyGC_PREV_MASK_FINALIZED: the GC's finalized flag in _gc_prev
178+ /// The GC's finalized flag: bit 0 of _gc_prev since Python 3.8, of gc_refs before
147179 /// </summary>
148180 private const nint FinalizedFlag = 1 ;
149181
150182 /// <summary>
151- /// _gc_prev, the last field of the GC header that precedes the object
183+ /// Offset from the object to the GC header word that holds <see cref="FinalizedFlag"/>
152184 /// </summary>
153- private static unsafe ref nint GCPrev ( BorrowedReference ob )
154- => ref * ( ( nint * ) ob . DangerousGetAddress ( ) - 1 ) ;
185+ private static nint finalizedFlagOffset ;
186+
187+ private static unsafe ref nint FinalizedFlagWord ( BorrowedReference ob )
188+ => ref * ( nint * ) ( ( byte * ) ob . DangerousGetAddress ( ) + finalizedFlagOffset ) ;
189+
190+ private static nint GetFinalizedFlagOffset ( )
191+ {
192+ if ( Runtime . PyVersion >= new Version ( 3 , 8 ) )
193+ {
194+ // _gc_prev, the last word of the GC header that precedes the object
195+ return - IntPtr . Size ;
196+ }
197+
198+ // Python 3.7: gc_refs, the third word of a GC header padded to the platform's
199+ // long double alignment. sys.getsizeof adds that header to __sizeof__.
200+ using var list = Runtime . PyList_New ( 0 ) ;
201+ using var sizeOf = Runtime . PyObject_GetAttrString ( list . Borrow ( ) , "__sizeof__" ) ;
202+ using var noArgs = Runtime . PyTuple_New ( 0 ) ;
203+ using var size = Runtime . PyObject_CallObject ( sizeOf . BorrowOrThrow ( ) , noArgs . Borrow ( ) ) ;
204+ using var getSizeOfArgs = Runtime . PyTuple_New ( 1 ) ;
205+ Runtime . PyTuple_SetItem ( getSizeOfArgs . Borrow ( ) , 0 , list . Borrow ( ) ) ;
206+ using var sizeWithGCHeader = Runtime . PyObject_CallObject (
207+ Runtime . PySys_GetObject ( "getsizeof" ) , getSizeOfArgs . Borrow ( ) ) ;
208+ nint gcHeaderSize = Runtime . PyLong_AsSignedSize_t ( sizeWithGCHeader . BorrowOrThrow ( ) )
209+ - Runtime . PyLong_AsSignedSize_t ( size . BorrowOrThrow ( ) ) ;
210+ return - gcHeaderSize + 2 * IntPtr . Size ;
211+ }
155212
156213 private static void ReplaceGCHandle ( BorrowedReference ob , CLRObject self , GCHandleType type )
157214 {
158- if ( type == GCHandleType . Weak )
215+ if ( type != GCHandleType . Normal )
159216 {
160217 WeaklyHeldWrappers . AddOrUpdate ( self . inst , self ) ;
161218 }
@@ -191,6 +248,7 @@ internal static NewReference ToPython(IPythonDerivedType obj)
191248 return default ;
192249 }
193250
251+ ReturnedToPython . Remove ( self . DangerousGetAddress ( ) ) ;
194252 if ( KeptByManagedObject . Remove ( self . DangerousGetAddress ( ) ) )
195253 {
196254 // Python takes over the reference the .NET object kept in tp_finalize
@@ -1009,16 +1067,20 @@ public static void PyFinalize(IPythonDerivedType obj)
10091067 // the C# object is being destroyed which must mean there are no more
10101068 // references to the Python object as well
10111069 var self = GetPyObj ( obj ) ;
1012- Finalizer . Instance . AddDerivedFinalizedObject ( ref self . RawObj , self . Run ) ;
1070+ Finalizer . Instance . AddDerivedFinalizedObject ( ref self . RawObj , self . Run , obj ) ;
10131071 }
10141072
1015- internal static void Finalize ( IntPtr derived )
1073+ internal static void Finalize ( IntPtr derived , object ? managed = null )
10161074 {
10171075 if ( ClassDerivedObject . KeptByManagedObject . Remove ( derived ) )
10181076 {
1019- // the Python object may still be part of a cycle: Python frees it once nothing references it
1077+ // tp_dealloc frees the Python object if this was its last reference
10201078 ClassDerivedObject . ReleasedByManagedObject . Add ( derived ) ;
10211079 Runtime . XDecref ( StolenReference . DangerousFromPointer ( derived ) ) ;
1080+ if ( ClassDerivedObject . ReleasedByManagedObject . Remove ( derived ) && managed is not null )
1081+ {
1082+ ClassDerivedObject . ReturnToPython ( new BorrowedReference ( derived ) , managed ) ;
1083+ }
10221084 return ;
10231085 }
10241086
0 commit comments