GCHandle Struct

Definition

提供用于从非托管内存访问托管对象的方法。Provides a way to access a managed object from unmanaged memory.

public value class GCHandle
public struct GCHandle
[System.Runtime.InteropServices.ComVisible(true)]
public struct GCHandle
type GCHandle = struct
Public Structure GCHandle
Inheritance
GCHandle
Attributes

Examples

下面的示例演示一个 App 类,该类使用 GCHandle.Alloc 方法创建托管对象的句柄,这会阻止收集托管的对象。The following example shows an App class that creates a handle to a managed object using the GCHandle.Alloc method, which prevents the managed object from being collected. EnumWindows 方法的调用会传递委托和托管对象(两者都声明为托管类型,但不显示),并将句柄强制转换为 IntPtrA call to the EnumWindows method passes a delegate and a managed object (both declared as managed types, but not shown), and casts the handle to an IntPtr. 非托管函数将该类型作为回调函数的参数传递回调用方。The unmanaged function passes the type back to the caller as a parameter of the callback function.

using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;

public delegate bool CallBack(int handle, IntPtr param);

internal static class NativeMethods
{
    // passing managed object as LPARAM
    // BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);

    [DllImport("user32.dll")]
    internal static extern bool EnumWindows(CallBack cb, IntPtr param);
}

public class App
{
    public static void Main()
    {
        Run();
    }

    [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
    public static void Run()
    {
        TextWriter tw = Console.Out;
        GCHandle gch = GCHandle.Alloc(tw);

        CallBack cewp = new CallBack(CaptureEnumWindowsProc);

        // platform invoke will prevent delegate to be garbage collected
        // before call ends

        NativeMethods.EnumWindows(cewp, GCHandle.ToIntPtr(gch));
        gch.Free();
    }

    private static bool CaptureEnumWindowsProc(int handle, IntPtr param)
    {
        GCHandle gch = GCHandle.FromIntPtr(param);
        TextWriter tw = (TextWriter)gch.Target;
        tw.WriteLine(handle);
        return true;
    }
}
Imports System.IO
Imports System.Threading
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Security.Permissions

Public Delegate Function CallBack(ByVal handle As Integer, ByVal param As IntPtr) As Boolean


Friend Module NativeMethods

    ' passing managed object as LPARAM
    ' BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);
    <DllImport("user32.dll")>
    Friend Function EnumWindows(ByVal cb As CallBack, ByVal param As IntPtr) As Boolean
    End Function
End Module


Module App

    Sub Main()

        Run()

    End Sub

    <SecurityPermission(SecurityAction.Demand, UnmanagedCode:=True)>
    Sub Run()

        Dim tw As TextWriter = Console.Out
        Dim gch As GCHandle = GCHandle.Alloc(tw)

        Dim cewp As CallBack
        cewp = AddressOf CaptureEnumWindowsProc

        ' platform invoke will prevent delegate to be garbage collected
        ' before call ends
        NativeMethods.EnumWindows(cewp, GCHandle.ToIntPtr(gch))
        gch.Free()

    End Sub


    Function CaptureEnumWindowsProc(ByVal handle As Integer, ByVal param As IntPtr) As Boolean
        Dim gch As GCHandle = GCHandle.FromIntPtr(param)
        Dim tw As TextWriter = CType(gch.Target, TextWriter)
        tw.WriteLine(handle)
        Return True

    End Function
End Module

Remarks

GCHandle 结构与 GCHandleType 枚举一起使用,以创建对应于任何托管对象的句柄。The GCHandle structure is used with the GCHandleType enumeration to create a handle corresponding to any managed object. 此句柄可以是以下四种类型之一: WeakWeakTrackResurrectionNormalPinnedThis handle can be one of four types: Weak, WeakTrackResurrection, Normal, or Pinned. 如果分配了句柄,则在非托管客户端持有唯一引用时,可以使用它来防止垃圾回收器收集托管的对象。When the handle has been allocated, you can use it to prevent the managed object from being collected by the garbage collector when an unmanaged client holds the only reference. 如果没有这样的句柄,则在代表非托管客户端完成其工作之前,垃圾回收器可以收集该对象。Without such a handle, the object can be collected by the garbage collector before completing its work on behalf of the unmanaged client.

你还可以使用 GCHandle 来创建一个固定的对象,该对象返回内存地址以防止垃圾回收器将对象移动到内存中。You can also use GCHandle to create a pinned object that returns a memory address to prevent the garbage collector from moving the object in memory.

如果句柄超出范围,则必须通过调用 Free 方法来显式释放该句柄;否则,可能会发生内存泄漏。When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. 当你释放固定的句柄时,关联的对象将被取消固定,并且如果没有其他引用,就会成为垃圾回收的条件。When you free a pinned handle, the associated object will be unpinned and will become eligible for garbage collection, if there are no other references to it.

Properties

IsAllocated

获取一个值,该值指示是否分配了句柄。Gets a value indicating whether the handle is allocated.

Target

获取或设置该句柄表示的对象。Gets or sets the object this handle represents.

Methods

AddrOfPinnedObject()

Pinned 句柄中检索对象数据的地址。Retrieves the address of object data in a Pinned handle.

Alloc(Object)

为指定的对象分配 Normal 句柄。Allocates a Normal handle for the specified object.

Alloc(Object, GCHandleType)

为指定的对象分配指定类型的句柄。Allocates a handle of the specified type for the specified object.

Equals(Object)

确定指定的 GCHandle 对象是否等同于当前的 GCHandleDetermines whether the specified GCHandle object is equal to the current GCHandle object.

Free()

释放 GCHandleReleases a GCHandle.

FromIntPtr(IntPtr)

返回从某个托管对象的句柄创建的新 GCHandle 对象。Returns a new GCHandle object created from a handle to a managed object.

GetHashCode()

返回当前 GCHandle 对象的标识符。Returns an identifier for the current GCHandle object.

ToIntPtr(GCHandle)

返回 GCHandle 对象的内部整数表示形式。Returns the internal integer representation of a GCHandle object.

Operators

Equality(GCHandle, GCHandle)

返回一个值,该值指示两个 GCHandle 对象是否相等。Returns a value indicating whether two GCHandle objects are equal.

Explicit(GCHandle to IntPtr)

GCHandle 以内部整数表示形式存储。A GCHandle is stored using an internal integer representation.

Explicit(IntPtr to GCHandle)

GCHandle 以内部整数表示形式存储。A GCHandle is stored using an internal integer representation.

Inequality(GCHandle, GCHandle)

返回一个值,该值指示两个 GCHandle 对象是否不相等。Returns a value indicating whether two GCHandle objects are not equal.

Applies to

See also