如何动态加载和卸载本机DLL文件?

我有一个错误的第三方DLL文件,在执行一段时间后,开始抛出访问冲突exception。 当发生这种情况时,我想重新加载该DLL文件。 我怎么做?

试试这个

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr LoadLibrary(string libname); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool FreeLibrary(IntPtr hModule); //Load IntPtr Handle = LoadLibrary(fileName); if (Handle == IntPtr.Zero) { int errorCode = Marshal.GetLastWin32Error(); throw new Exception(string.Format("Failed to load library (ErrorCode: {0})",errorCode)); } //Free if(Handle != IntPtr.Zero) FreeLibrary(Handle); 

如果要首先调用函数,则必须创建与此函数匹配的delegeate,然后使用WinApi GetProcAddress

 [DllImport("kernel32.dll", CharSet = CharSet.Ansi)] private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); IntPtr funcaddr = GetProcAddress(Handle,functionName); YourFunctionDelegate function = Marshal.GetDelegateForFunctionPointer(funcaddr,typeof(YourFunctionDelegate )) as YourFunctionDelegate ; function.Invoke(pass here your parameters); 

创建通过COM或其他IPC机制进行通信的工作进程。 然后当DLL死亡时,您可以重新启动工作进程。

加载DLL,调用它,然后卸载它直到它消失。

我在这里修改了VB.Net示例中的以下代码。

  [DllImport("powrprof.dll")] static extern bool IsPwrHibernateAllowed(); [DllImport("kernel32.dll")] static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32.dll")] static extern bool LoadLibraryA(string hModule); [DllImport("kernel32.dll")] static extern bool GetModuleHandleExA(int dwFlags, string ModuleName, ref IntPtr phModule); static void Main(string[] args) { Console.WriteLine("Is Power Hibernate Allowed? " + DoIsPwrHibernateAllowed()); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } private static bool DoIsPwrHibernateAllowed() { LoadLibraryA("powrprof.dll"); var result = IsPwrHibernateAllowed(); var hMod = IntPtr.Zero; if (GetModuleHandleExA(0, "powrprof", ref hMod)) { while (FreeLibrary(hMod)) { } } return result; }