对于本机 DLL,您可以创建以下静态类:
internal static class NativeWinAPI
{
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
internal static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule,
string procedureName);
}
然后按如下方式使用它:
// DLLFileName is, say, "MyLibrary.dll"
IntPtr hLibrary = NativeWinAPI.LoadLibrary(DLLFileName);
if (hLibrary != IntPtr.Zero) // DLL is loaded successfully
{
// FunctionName is, say, "MyFunctionName"
IntPtr pointerToFunction = NativeWinAPI.GetProcAddress(hLibrary, FunctionName);
if (pointerToFunction != IntPtr.Zero)
{
MyFunctionDelegate function = (MyFunctionDelegate)Marshal.GetDelegateForFunctionPointer(
pointerToFunction, typeof(MyFunctionDelegate));
function(123);
}
NativeWinAPI.FreeLibrary(hLibrary);
}
MyFunctionDelegate
一个在哪里delegate
。例如:
delegate void MyFunctionDelegate(int i);