SLa*_*aks 15
调用LoadLibraryAPI函数:
[DllImport("kernel32", SetLastError=true)]
static extern IntPtr LoadLibrary(string lpFileName);
static bool CheckLibrary(string fileName) {
return LoadLibrary(fileName) == IntPtr.Zero;
}
Run Code Online (Sandbox Code Playgroud)
在 .NET 中使用平台调用时,可以使用以下Marshal.PrelinkAll(Type)方法:
设置任务提供早期初始化,并在调用目标方法时自动执行。首次任务包括以下内容:
验证平台调用元数据的格式是否正确。
验证所有托管类型是否都是平台调用函数的有效参数。
定位非托管 DLL 并将其加载到进程中。
找到流程中的入口点。
正如您所看到的,除了 dll 是否存在之外,它还会执行其他检查,例如定位入口点(例如,进程中SomeMethod()是否SomeMethod2()实际存在,如以下代码所示)。
using System.Runtime.InteropServices;
public class MY_PINVOKES
{
[DllImport("some.dll")]
private static void SomeMethod();
[DllImport("some.dll")]
private static void SomeMethod2();
}
Run Code Online (Sandbox Code Playgroud)
然后使用try/catch策略来执行检查:
try
{
// MY_PINVOKES class where P/Invokes are
Marshal.PrelinkAll( typeof( MY_PINVOKES) );
}
catch
{
// Handle error, DLL or Method may not exist
}
Run Code Online (Sandbox Code Playgroud)