GCHandle 구조체

정의

관리되지 않는 메모리에서 관리되는 개체에 액세스하기 위한 방법을 제공합니다.

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)
상속
GCHandle
특성
구현

예제

다음 예제에서는 관리되는 개체가 수집되지 않도록 하는 메서드를 사용하여 GCHandle.Alloc 관리되는 개체에 대한 핸들을 만드는 클래스를 보여 App 줍니다. 메서드 호출은 EnumWindows 대리자와 관리되는 개체(둘 다 관리되는 형식으로 선언되었지만 표시되지 않음)를 전달하고 핸들을 캐스팅 IntPtr합니다. 관리되지 않는 함수는 콜백 함수의 매개 변수로 형식을 호출자에게 다시 전달합니다.

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

설명

구조체 GCHandle 는 모든 관리되는 개체에 GCHandleType 해당하는 핸들을 만들기 위해 열거형과 함께 사용됩니다. 이 핸들은 네 가지 유형 Weak``WeakTrackResurrection``Normal``Pinned중 하나일 수 있습니다. 핸들이 할당된 경우 관리되지 않는 클라이언트가 유일한 참조를 보유할 때 관리되는 개체가 가비지 수집기에서 수집되지 않도록 방지할 수 있습니다. 이러한 핸들이 없으면 관리되지 않는 클라이언트를 대신하여 작업을 완료하기 전에 가비지 수집기에서 개체를 수집할 수 있습니다.

가비지 수집기가 메모리에서 개체를 이동하지 못하도록 메모리 주소를 반환하는 고정된 개체를 만드는 데 사용할 GCHandle 수도 있습니다.

핸들이 범위를 벗어나면 메서드를 호출 Free 하여 명시적으로 해제해야 합니다. 그렇지 않으면 메모리 누수가 발생할 수 있습니다. 고정된 핸들을 해제하면 연결된 개체가 고정 해제되고 다른 참조가 없는 경우 가비지 수집에 적합하게 됩니다.

속성

IsAllocated

핸들이 할당되는지 여부를 나타내는 값을 가져옵니다.

Target

이 핸들이 나타나는 개체를 가져오거나 설정합니다.

메서드

AddrOfPinnedObject()

Pinned 핸들에 있는 개체 데이터의 주소를 검색합니다.

Alloc(Object)

지정된 개체의 Normal 핸들을 할당합니다.

Alloc(Object, GCHandleType)

지정된 개체에 특정 형식의 핸들을 할당합니다.

Equals(GCHandle)

현재 인스턴스가 동일한 형식의 다른 인스턴스와 같은지 여부를 나타냅니다.

Equals(Object)

지정된 GCHandle 개체가 현재 GCHandle 개체와 같은지 여부를 확인합니다.

Free()

GCHandle을 해제합니다.

FromIntPtr(IntPtr)

관리되는 개체에 대한 핸들에서 만든 새 GCHandle 개체를 반환합니다.

GetHashCode()

현재 GCHandle 개체에 대한 식별자를 반환합니다.

ToIntPtr(GCHandle)

GCHandle 개체의 내부 정수 표현을 반환합니다.

연산자

Equality(GCHandle, GCHandle)

GCHandle 개체가 같은지 여부를 나타내는 값을 반환합니다.

Explicit(GCHandle to IntPtr)

GCHandle은 내부 정수 표현을 사용하여 저장됩니다.

Explicit(IntPtr to GCHandle)

GCHandle은 내부 정수 표현을 사용하여 저장됩니다.

Inequality(GCHandle, GCHandle)

GCHandle 개체가 다른지 여부를 나타내는 값을 반환합니다.

적용 대상

추가 정보