GCHandle.FromIntPtr メソッド
アセンブリ: mscorlib (mscorlib.dll 内)

Dim value As IntPtr Dim returnValue As GCHandle returnValue = GCHandle.FromIntPtr(value)
戻り値
値パラメータに対応する新しい GCHandle オブジェクト。


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 Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- GCHandle.FromIntPtr メソッドのページへのリンク