gpt4 book ai didi

c# - 这个CIL有什么问题?

转载 作者:太空狗 更新时间:2023-10-29 22:59:30 25 4
gpt4 key购买 nike

我正在通过 Cecil 生成一些代码。代码生成没有错误,但是当我尝试加载程序集时,我得到:

An unhandled exception of type 'System.InvalidProgramException' occurred in DataSerializersTest.exe

Additional information: Common Language Runtime detected an invalid program.

这是生成的 IL:

.method public static 
class Data.FooData Read (
class [mscorlib]System.IO.BinaryReader input
) cil managed
{
// Method begins at RVA 0x3a58
// Code size 60 (0x3c)
.maxstack 3
.locals (
[0] class Data.FooData,
[1] valuetype [System.Runtime]System.Nullable`1<int32>
)

IL_0000: newobj instance void Data.FooData::.ctor()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: callvirt instance bool [System.IO]System.IO.BinaryReader::ReadBoolean()
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: brtrue.s IL_001f

IL_0012: ldarg.0
IL_0013: callvirt instance int32 [System.IO]System.IO.BinaryReader::ReadInt32()
IL_0018: newobj instance void valuetype [System.Runtime]System.Nullable`1<int32>::.ctor(!0)
IL_001d: br.s IL_0028

IL_001f: nop
IL_0020: ldloca.s 1
IL_0022: initobj valuetype [System.Runtime]System.Nullable`1<int32>

IL_0028: nop
IL_0029: callvirt instance void Data.FooData::set_I(valuetype [System.Runtime]System.Nullable`1<int32>)
IL_002e: ldloc.0
IL_002f: ldarg.0
IL_0030: callvirt instance string [System.IO]System.IO.BinaryReader::ReadString()
IL_0035: callvirt instance void Data.FooData::set_Name(string)
IL_003a: ldloc.0
IL_003b: ret
} // end of method FooDataReader::Read

等效的 C# 代码如下所示:

public static FooData Read(BinaryReader input)
{
var result = new FooData();

if (input.ReadBoolean())
{
result.I = input.ReadInt32();
}
else
{
result.I = null;
}

result.Name = input.ReadString();

return result;
}

我已经研究过 IL 好几次,它对我来说很有意义。它与 C# 编译器为上述 C# 代码生成的内容不同,但我想了解我生成的 IL 有什么问题。谁能告诉我?

最佳答案

我想我已经发现了。 initobj 不会将新初始化的对象留在计算堆栈上 - 而 newobj做。所以当 IL_0028 时堆栈是不平衡的达到 - 如果我们已经走了 newobj路线,那么我们在堆栈上有两个项目( FooDataNullable<int> )。如果我们走了 initobj路线,那么我们所拥有的就是FooData堆栈上的对象引用。需要重新加载本地1 :

IL_0022: initobj valuetype [System.Runtime]System.Nullable`1<int32>
ldloc.1
IL_0028: nop

关于c# - 这个CIL有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20881417/

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