c#代码无法访问
本文关键字:访问 代码 | 更新日期: 2023-09-27 18:09:27
我正在制作这个dll加载器。我似乎不能让它返回一个假语句。
就评论一下你是怎么修复的,这样我就能理解你是怎么修复的了?
提示:代码不可达
在else语句
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
internal class Program
{
[DllImport("msvcrt.dll")]
static extern bool system(string str);
private static void Main()
{
Console.Title = "Load DLL Test";
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("CREATED BY TOXLP'n");
Console.WriteLine("PLEASE TYPE A DLL NAME");
Console.WriteLine("======================");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("EXAMPLE:");
Console.WriteLine("NAME.DLL");
Console.WriteLine("======================");
Console.ForegroundColor = ConsoleColor.Green;
var dllname = Console.ReadLine();
var pDll = NativeMethods.LoadLibrary(dllname);
if (pDll != null)
{
Console.WriteLine(@"LOADED!");
}
else
{
Console.WriteLine(@"FAILED!");
}
system("pause");
}
}
问题是IntPtr
是值类型,而不是引用,因此它不能为空。如果你想检查指针是否从未设置(意味着操作失败),你应该检查指针是否为零
ptr == IntPtr.Zero
我怀疑var pDll = NativeMethods.LoadLibrary(dllname);
返回一个非空对象,例如struct
。因此,它永远不能为空。
您可能要检查它不是default
而不是(可能…)
pDll != null总是True,这就是代码不可达的原因。不能为False,因为没有加载pDll == IntPtr。0