我觉得最好的办法来说明这个feature是通过例子:
using System.Runtime.InteropServices;
using System;
public class TestClass
{
public static void Main(String[] args)
{
IntPtr user32 = LoadLibrary("user32.dll");
IntPtr procaddr = GetProcAddress(user32, "MessageBoxW");
MyMessageBox mbx = (MyMessageBox)Marshal.GetDelegateForFunctionPointer(procaddr, typeof(MyMessageBox));
mbx(IntPtr.Zero, "Hello, World", "A Test Run", 0);
// MessageBox(IntPtr.Zero. "Hello, World", "A Test Run", 0);
}
internal delegate int MyMessageBox(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)]String text, [MarshalAs(UnmanagedType.LPWStr)]String Caption, int type);
/*
[DllImport("user32.dll")]
internal static extern int MessageBox(IntPtr hwnd, String text, String Caption, int type);
*/
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String procname);
}
GetDelegateForFunctionPointer的文档在http://lab.msdn.microsoft.com/library/en-us/cpref/html/M_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointer_2_52ec9e31.asp