示例代码:
public class ExecuteDLL : Form { private IntPtr hModule = IntPtr.Zero; //申明外部API [DllImport("kernel32.dll")] static extern IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32.dll")] static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); [DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)] static extern bool FreeLibrary(IntPtr hModule); //申明委托 private delegate IntPtr TestFunc(int window); private void test() { string strDLLPath = ".\\tests.dll"; hModule = LoadLibrary(strDLLPath); if (hModule.Equals(IntPtr.Zero)) { MessageBox.Show("导入DLL失败"); return; } TestFuncfarProc = (TestFunc)this.GetFunctionAddress(hModule, "TestFunc", typeof(TestFunc)); if (farProc == null) { FreeLibrary(hModule); hModule = IntPtr.Zero; return; } //利用委托执行DLL文件中的接口方法 farProc(hModule, IntPtr.Zero, IntPtr.Zero, null, null, strNo); FreeLibrary(hModule); hModule = IntPtr.Zero; } }