GCHandle.Target プロパティ
アセンブリ: mscorlib (mscorlib.dll 内)

ハンドルが表すオブジェクト。


GCHandle.Alloc メソッドを使用してマネージ オブジェクトへのハンドルを作成する App クラスの例を次に示します。これによって、マネージ オブジェクトはガベージ コレクションの対象から除外されます。EnumWindows メソッドの呼び出しは、デリゲートとマネージ オブジェクト (両方ともマネージ型として宣言されていますが、ここでは示されていません) を渡し、ハンドルを IntPtr にキャストします。このアンマネージ関数は、コールバック関数のパラメータとして型を呼び出し元に戻します。
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
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; } }


Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- GCHandle.Target プロパティのページへのリンク