GCHandle Structure
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Fournit un moyen d’accéder à un objet managé à partir de la mémoire non managée.
public value class GCHandle
public struct GCHandle
[System.Runtime.InteropServices.ComVisible(true)]
public struct GCHandle
type GCHandle = struct
[<System.Runtime.InteropServices.ComVisible(true)>]
type GCHandle = struct
Public Structure GCHandle
- Héritage
- Attributs
Exemples
L’exemple suivant montre une classe qui crée un App handle sur un objet managé à l’aide de la GCHandle.Alloc méthode, ce qui empêche la collecte de l’objet managé. Un appel à la EnumWindows méthode transmet un délégué et un objet managé (tous deux déclarés en tant que types managés, mais non affichés) et convertit le handle en un IntPtr. La fonction non managée transmet le type à l’appelant en tant que paramètre de la fonction de rappel.
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
Remarques
La GCHandle structure est utilisée avec l’énumération GCHandleType pour créer un handle correspondant à n’importe quel objet managé. Ce handle peut être l’un des quatre types suivants : Weak, , WeakTrackResurrectionNormalou Pinned. Lorsque le handle a été alloué, vous pouvez l’utiliser pour empêcher la collecte de l’objet managé par le garbage collector lorsqu’un client non géré contient la seule référence. Sans ce type de handle, l’objet peut être collecté par le garbage collector avant d’effectuer son travail au nom du client non managé.
Vous pouvez également utiliser GCHandle pour créer un objet épinglé qui retourne une adresse mémoire pour empêcher le garbage collector de déplacer l’objet en mémoire.
Lorsque le handle sort de portée, vous devez le libérer explicitement en appelant la Free méthode ; sinon, les fuites de mémoire peuvent se produire. Lorsque vous libérez un handle épinglé, l’objet associé est non épinglé et devient éligible au garbage collection, s’il n’y a pas d’autres références à celui-ci.
Propriétés
| Nom | Description |
|---|---|
| IsAllocated |
Obtient une valeur indiquant si le handle est alloué. |
| Target |
Obtient ou définit l’objet que représente ce handle. |
Méthodes
| Nom | Description |
|---|---|
| AddrOfPinnedObject() |
Récupère l’adresse des données d’objet dans un Pinned handle. |
| Alloc(Object, GCHandleType) |
Alloue un handle du type spécifié pour l’objet spécifié. |
| Alloc(Object) |
Alloue un Normal handle pour l’objet spécifié. |
| Equals(Object) |
Détermine si l’objet spécifié GCHandle est égal à l’objet actuel GCHandle . |
| Free() |
Libère un GCHandle. |
| FromIntPtr(IntPtr) |
Retourne un nouvel GCHandle objet créé à partir d’un handle vers un objet managé. |
| GetHashCode() |
Retourne un identificateur pour l’objet actif GCHandle . |
| ToIntPtr(GCHandle) |
Retourne la représentation entière interne d’un GCHandle objet. |
Opérateurs
| Nom | Description |
|---|---|
| Equality(GCHandle, GCHandle) |
Retourne une valeur indiquant si deux GCHandle objets sont égaux. |
| Explicit(GCHandle to IntPtr) |
Un GCHandle est stocké à l’aide d’une représentation entière interne. |
| Explicit(IntPtr to GCHandle) |
Un GCHandle est stocké à l’aide d’une représentation entière interne. |
| Inequality(GCHandle, GCHandle) |
Retourne une valeur indiquant si deux GCHandle objets ne sont pas égaux. |