GCHandle Struct

Definizione

Fornisce un modo per accedere a un oggetto gestito dalla memoria non gestita.

public value class GCHandle
public value class GCHandle : IEquatable<System::Runtime::InteropServices::GCHandle>
public struct GCHandle
public struct GCHandle : IEquatable<System.Runtime.InteropServices.GCHandle>
[System.Runtime.InteropServices.ComVisible(true)]
public struct GCHandle
type GCHandle = struct
[<System.Runtime.InteropServices.ComVisible(true)>]
type GCHandle = struct
Public Structure GCHandle
Public Structure GCHandle
Implements IEquatable(Of GCHandle)
Ereditarietà
GCHandle
Attributi
Implementazioni

Esempio

Nell'esempio seguente viene illustrata una App classe che crea un handle per un oggetto gestito usando il GCHandle.Alloc metodo , che impedisce la raccolta dell'oggetto gestito. Una chiamata al EnumWindows metodo passa un delegato e un oggetto gestito (entrambi dichiarati come tipi gestiti, ma non visualizzati) ed esegue il cast dell'handle a un IntPtroggetto . La funzione non gestita passa nuovamente il tipo al chiamante come parametro della funzione di callback.

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

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();
    }

    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

Commenti

La GCHandle struttura viene utilizzata con l'enumerazione GCHandleType per creare un handle corrispondente a qualsiasi oggetto gestito. Questo handle può essere di quattro tipi: Weak, WeakTrackResurrection, Normalo Pinned. Quando l'handle è stato allocato, è possibile usarlo per impedire che l'oggetto gestito venga raccolto dal Garbage Collector quando un client non gestito contiene l'unico riferimento. Senza un handle di questo tipo, l'oggetto può essere raccolto dal Garbage Collector prima di completarne il lavoro per conto del client non gestito.

È anche possibile usare GCHandle per creare un oggetto aggiunto che restituisce un indirizzo di memoria per impedire al Garbage Collector di spostare l'oggetto in memoria.

Quando l'handle esce dall'ambito, è necessario rilasciarlo in modo esplicito chiamando il Free metodo . In caso contrario, potrebbero verificarsi perdite di memoria. Quando si libera un handle bloccato, l'oggetto associato verrà rimosso e diventerà idoneo per l'operazione di Garbage Collection, se non sono presenti altri riferimenti.

Proprietà

Nome Descrizione
IsAllocated

Ottiene un valore che indica se l'handle è allocato.

Target

Ottiene o imposta l'oggetto rappresentato da questo handle.

Metodi

Nome Descrizione
AddrOfPinnedObject()

Recupera l'indirizzo dei dati dell'oggetto in un Pinned handle.

Alloc(Object, GCHandleType)

Alloca un handle del tipo specificato per l'oggetto specificato.

Alloc(Object)

Alloca un Normal handle per l'oggetto specificato.

Equals(GCHandle)

Indica se l'istanza corrente è uguale a un'altra istanza dello stesso tipo.

Equals(Object)

Determina se l'oggetto specificato GCHandle è uguale all'oggetto corrente GCHandle .

Free()

Rilascia un oggetto GCHandle.

FromIntPtr(IntPtr)

Restituisce un nuovo GCHandle oggetto creato da un handle a un oggetto gestito.

GetHashCode()

Restituisce un identificatore per l'oggetto corrente GCHandle .

ToIntPtr(GCHandle)

Restituisce la rappresentazione intera interna di un GCHandle oggetto .

Operatori

Nome Descrizione
Equality(GCHandle, GCHandle)

Restituisce un valore che indica se due GCHandle oggetti sono uguali.

Explicit(GCHandle to IntPtr)

Un GCHandle oggetto viene archiviato utilizzando una rappresentazione interna di tipo Integer.

Explicit(IntPtr to GCHandle)

Un GCHandle oggetto viene archiviato utilizzando una rappresentazione interna di tipo Integer.

Inequality(GCHandle, GCHandle)

Restituisce un valore che indica se due GCHandle oggetti non sono uguali.

Si applica a

Vedi anche