在.NET环境中使用DllImport
时,可以通过以下方法检查DLL是否已加载:
DllImport
是.NET平台调用非托管DLL函数的机制。检查DLL是否已加载的核心是查询当前进程的模块列表。
Process
模块枚举通过Process.GetCurrentProcess().Modules
遍历已加载模块:
using System.Diagnostics;
using System.Linq;
bool IsDllLoaded(string dllName)
{
return Process.GetCurrentProcess()
.Modules
.Cast<ProcessModule>()
.Any(m => m.ModuleName.Equals(dllName, StringComparison.OrdinalIgnoreCase));
}
// 示例:检查"user32.dll"
bool isLoaded = IsDllLoaded("user32.dll");
GetModuleHandle
Win32 API更高效的方式是直接调用Windows API:
using System;
using System.Runtime.InteropServices;
class DllChecker
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
public static bool IsDllLoaded(string dllName)
{
return GetModuleHandle(dllName) != IntPtr.Zero;
}
}
// 使用示例
bool isLoaded = DllChecker.IsDllLoaded("kernel32.dll");
GetModuleHandle
仅检查已加载模块,不会主动搜索文件系统。.dll
)正确。DllImport
,DLL可能在首次调用时才加载。false
但DLL实际存在?Dependency Walker
)检查依赖链。通过LoadLibrary
显式加载:
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr LoadLibrary(string lpFileName);
// 强制加载示例
IntPtr handle = LoadLibrary("MyLib.dll");
if (handle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
Console.WriteLine($"加载失败,错误代码: {errorCode}");
}
GetModuleHandle
,性能更高。LoadLibrary
和错误处理可构建健壮的动态加载逻辑。