在验证一些包含返回指针的不安全方法的代码时,我遇到了这个问题。
该示例可以表示为:
public class A
{
public static unsafe int* GetAnswer()
{
int fakeValue = 42;
return &(fakeValue);
}
public static void Main()
{
int i = 0;
unsafe { i = *A.GetAnswer(); }
System.Console.WriteLine(i);
}
}
我正在使用两个独立的验证工具,即 ILVerify 和 Peverify。
重现步骤:
- 使用编译示例代码
csc example.cs /t:library /unsafe
- 核实
peverify example.dll
- 核实
ILVerify.exe -r C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll example.dll
2. 和 3. 都将导致以下错误消息:
[IL]:错误:[C:\src\test\example.dll : A::GetAnswer()][offset 0x00000006][found address of Int32] 堆栈上的预期数字类型。
[IL]:错误:[C:\src\test\example.dll : A::Main()][offset 0x00000009][found Native Int] 堆栈上需要 ByRef。2 验证 C:\src\test\example.dll 的错误
神秘的是,一切都按预期编译和运行,它不会验证。有没有人对为什么会这样有一些洞察力?