diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs
index 47e592d16..31975ff16 100644
--- a/src/runtime/Converter.cs
+++ b/src/runtime/Converter.cs
@@ -552,6 +552,10 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,
if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type))
{
+ if (tmp is IPythonDerivedType)
+ {
+ ClassDerivedObject.PassedToManaged(value);
+ }
result = tmp;
return true;
}
diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs
index 05c498443..9791bee72 100644
--- a/src/runtime/Finalizer.cs
+++ b/src/runtime/Finalizer.cs
@@ -154,19 +154,24 @@ internal void AddFinalizedObject(ref IntPtr obj, int run
obj = IntPtr.Zero;
}
- internal void AddDerivedFinalizedObject(ref IntPtr derived, int run)
+ /// Whether the object was queued, which it isn't while is false
+ internal bool AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false)
{
if (derived == IntPtr.Zero)
throw new ArgumentNullException(nameof(derived));
if (!Enable)
{
- return;
+ return false;
}
- var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run };
+ var pending = new PendingFinalization
+ {
+ PyObj = derived, RuntimeRun = run, Deferred = deferred, KeptReference = keptReference,
+ };
derived = IntPtr.Zero;
_derivedQueue.Enqueue(pending);
+ return true;
}
internal void AddFinalizedBuffer(ref Py_buffer buffer)
@@ -254,7 +259,7 @@ internal nint DisposeAll()
}
#pragma warning disable CS0618 // Type or member is obsolete. OK for internal use
- PythonDerivedType.Finalize(derived.PyObj);
+ PythonDerivedType.Finalize(derived.PyObj, derived.Deferred, derived.KeptReference);
#pragma warning restore CS0618 // Type or member is obsolete
collected++;
@@ -367,6 +372,14 @@ struct PendingFinalization
public IntPtr PyObj;
public BorrowedReference Ref => new(PyObj);
public int RuntimeRun;
+ ///
+ /// The .NET object of a Python derived type whose finalization waits until this is handled
+ ///
+ public object? Deferred;
+ ///
+ /// holds a reference to
+ ///
+ public bool KeptReference;
#if TRACE_ALLOC
public string StackTrace;
#endif
diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs
index bcf99bede..8b4a250c2 100644
--- a/src/runtime/Interop.cs
+++ b/src/runtime/Interop.cs
@@ -188,6 +188,9 @@ internal static ThunkInfo GetThunk(Delegate @delegate)
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void N_V(NewReference ob);
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ public delegate void B_V(BorrowedReference ob);
+
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int BPP_I32(BorrowedReference ob, IntPtr a1, IntPtr a2);
}
diff --git a/src/runtime/Native/ITypeOffsets.cs b/src/runtime/Native/ITypeOffsets.cs
index bae8636c5..3d19cb71e 100644
--- a/src/runtime/Native/ITypeOffsets.cs
+++ b/src/runtime/Native/ITypeOffsets.cs
@@ -52,6 +52,7 @@ interface ITypeOffsets
int tp_descr_set { get; }
int tp_dict { get; }
int tp_dictoffset { get; }
+ int tp_finalize { get; }
int tp_flags { get; }
int tp_free { get; }
int tp_getattro { get; }
diff --git a/src/runtime/Native/TypeOffset.cs b/src/runtime/Native/TypeOffset.cs
index 76196bcad..314f3c8f4 100644
--- a/src/runtime/Native/TypeOffset.cs
+++ b/src/runtime/Native/TypeOffset.cs
@@ -59,6 +59,7 @@ static partial class TypeOffset
internal static int tp_descr_set { get; private set; }
internal static int tp_dict { get; private set; }
internal static int tp_dictoffset { get; private set; }
+ internal static int tp_finalize { get; private set; }
internal static int tp_flags { get; private set; }
internal static int tp_free { get; private set; }
internal static int tp_getattro { get; private set; }
diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs
index daeacfcd7..f11a179da 100644
--- a/src/runtime/Types/ClassDerived.cs
+++ b/src/runtime/Types/ClassDerived.cs
@@ -5,6 +5,7 @@
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Python.Runtime.Native;
@@ -34,6 +35,33 @@ internal class ClassDerivedObject : ClassObject
private static Dictionary assemblyBuilders;
private static Dictionary, ModuleBuilder> moduleBuilders;
+ ///
+ /// Python objects whose .NET object holds one reference to them, taken in
+ ///
+ private static readonly HashSet KeptByManagedObject = new();
+ ///
+ /// Python objects that took back the reference their .NET object kept, in ,
+ /// while .NET may already be finalizing that .NET object
+ ///
+ private static readonly HashSet TakenBackByPython = new();
+ ///
+ /// Python objects whose .NET object was finalized while it held the reference taken in
+ /// , and that weren't passed to .NET since: the next time the GC finds
+ /// such an object unreachable, nothing else references it and the GC frees the cycle
+ ///
+ private static readonly HashSet ReturnedToPython = new();
+ ///
+ /// Guards , and
+ /// , which the .NET finalizer thread updates in
+ ///
+ ///
+ private static readonly object KeptLock = new();
+ ///
+ /// Nothing else references the wrapper of a .NET object its Python object holds weakly:
+ /// this keeps it alive as long as the .NET object
+ ///
+ private static readonly ConditionalWeakTable