我有一个有缺陷的第三方 DLL 文件,执行一段时间后开始抛出访问冲突异常。当发生这种情况时,我想重新加载该 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);
DllImport
时,这种方法不起作用。 - Poma加载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;
}