Skip to content

Add Dispose/IDisposable to GCHandle #54792

@Sergio0694

Description

@Sergio0694

Follow up from @jkotas's comment: #19459 (comment). The same issue also contains an extensive conversation about this proposal, with some practical use case scenarios as well (in particular, see this comment by @jkoritzinsky: #19459 (comment)).

Proposed API

namespace System.Runtime.InteropServices
{
      public struct GCHandle
+        : IDisposable
      {
+        public void Dispose();
      }
}

Usage Examples

// Given...
[DllImport("nativelib")]
public static unsafe extern void DoCallback(IntPtr state, delegate*<IntPtr, void> callback);

[UnmanagedCallersOnly]
public static void Callback(IntPtr state)
{
    GCHandle handle = GCHandle.FromIntPtr(state);
    object state = handle.Target;
}

// ...this PR would enable this
using (GCHandle handle = GCHandle.Alloc(state))
{
    DoCallback(handle, &Callback);
}

Risks

Copying/boxing a GChandle value and calling Dispose on each copy will still possibly result in a crash. This is the same behavior as other approved APIs already though (eg. DependentHandle), and it's a limitation with C# not having proper move semantics.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions