How to dynamically load and unload a native DLL file?
I have a buggy third-party DLL 开发者_运维技巧files that, after some time of execution, starts throwing the access violation exceptions. When that happens I want to reload that DLL file. How do I do that?
Try this
[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);
If you want to call functions first you must create delegate that matches this function and then use 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);
Create a worker process that communicates via COM or another IPC mechanism. Then when the DLL dies, you can just restart the worker process.
Load the dll, call it, and then unload it till it's gone.
I've adapted the following code from the VB.Net example here.
[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; }
精彩评论