gpt4 book ai didi

c# - 如何动态加载和卸载原生 DLL 文件?

转载 作者:太空狗 更新时间:2023-10-29 17:33:28 26 4
gpt4 key购买 nike

我有一个有问题的第三方 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);

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

关于c# - 如何动态加载和卸载原生 DLL 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6452951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com