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

时间:2011-06-23 10:59:16

标签: c# .net pinvoke

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

3 个答案:

答案 0 :(得分:22)

试试这个

[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);

如果要首先调用函数,则必须创建与此函数匹配的委托,然后使用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);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

我已经从VB.Net示例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;
  }