Compartir a través de


Método GCHandle.Alloc (Object)

 

Publicado: noviembre de 2016

Asigna un identificador Normal para el objeto especificado.

Espacio de nombres:   System.Runtime.InteropServices
Ensamblado:  mscorlib (en mscorlib.dll)

Sintaxis

[SecurityCriticalAttribute]
public static GCHandle Alloc(
    object value
)
public:
[SecurityCriticalAttribute]
static GCHandle Alloc(
    Object^ value
)
[<SecurityCriticalAttribute>]
static member Alloc : 
        value:Object -> GCHandle
<SecurityCriticalAttribute>
Public Shared Function Alloc (
    value As Object
) As GCHandle

Parámetros

Valor devuelto

Type: System.Runtime.InteropServices.GCHandle

Nuevo GCHandle que protege al objeto de la recolección de elementos no utilizados.GCHandle debe liberarse con Free cuando ya no sea necesario.

Excepciones

Exception Condition
ArgumentException

No se puede anclar una instancia con miembros primitivos (espacio).

Comentarios

Normal identificadores son opacos, lo que significa que no puede resolver la dirección del objeto que contiene a través del identificador.

Ejemplos

El ejemplo siguiente muestra un App clase que crea un identificador para un objeto administrado mediante el GCHandle.Alloc método, que impide que el objeto administrado sea recogido. Una llamada a la EnumWindows método pasa un delegado y un objeto administrado (ambos se declaran como tipos administrados, pero no se muestra) y convierte el identificador a una IntPtr. La función no administrada, pasa el tipo al llamador como parámetro de la función de devolución de llamada.

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

public class LibWrap
{
    // passing managed object as LPARAM
    // BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);

    [DllImport("user32.dll")]
    public 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 = System.Console.Out;
        GCHandle gch = GCHandle.Alloc(tw);

        CallBack cewp = new CallBack(CaptureEnumWindowsProc);

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

        LibWrap.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
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


Module LibWrap

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


Module App

    Sub Main()
    Run()

    End Sub

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

        Dim tw As TextWriter = System.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
        LibWrap.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

Seguridad

SecurityCriticalAttribute

requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

Información de versión

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

Ver también

GCHandleType
Alloc Sobrecarga
Estructura GCHandle
Espacio de nombres System.Runtime.InteropServices

Volver al principio