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

| 我有一个有问题的第三方DLL文件,在执行了一段时间后,该文件开始引发访问冲突异常。发生这种情况时,我想重新加载该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);
如果要首先调用函数,则必须创建与该函数匹配的委托,然后使用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;
  }
    

要回复问题请先登录注册