string message = "Hello World!"; GCHandle handle = GCHandle.Alloc(message, GCHandleType.Pinned); IntPtr pointer = handle.AddrOfPinnedObject(); // Use pointer with unmanaged code handle.Free();
public delegate int MyDelegate(int arg); GCHandle handle = GCHandle.Alloc(new MyDelegate(DoSomething), GCHandleType.Normal); IntPtr pointer = Marshal.GetFunctionPointerForDelegate(handle.Target as MyDelegate); // Use pointer with unmanaged code handle.Free(); int DoSomething(int arg) { // Do something return arg; }This code creates a GCHandle for a delegate to a managed function and gets a function pointer for it. The function pointer can be passed to unmanaged code to invoke the managed function. The System.Runtime.InteropServices namespace is part of the .NET Framework class library.