Mono.Cecil - 无法导入构造函数

时间:2014-11-23 18:07:03

标签: mono.cecil

我已经在课堂上注入了一个空方法。我现在正试图用以下简单的代码填充它:

Affliction test = new Affliction ();
if (test != null)
    Console.AddMessage ("not null");

我已经使用Reflexil将此片段转换为ILCode,并且当我使用Reflexil本身注入它时它可以正常工作。

但是,当我向Cecil注入相同的ilcode指令时,运行程序时出错,我也无法在.Net Reflector中打开它。 这是我正在注入的ILcode:

IL_0000: newobj System.Void Affliction::.ctor()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldnull
IL_0008: call System.Boolean Affliction::op_Inequality(Affliction,Affliction)
IL_0013: brfalse.s IL_0025
IL_0015: ldstr "not null"
IL_0020: call System.Void Console:AddMessage(System.String)
IL_0025: ret

我就是这样做的:

System.Reflection.ConstructorInfo constrInfo = typeof(Affliction).GetConstructors()[0];
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Newobj, mainMod.Import (constrInfo)));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc_0));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Call, mainMod.Import(typeof(Affliction).GetMethod ("op_Inequality"))));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse_S, newMethod.Body.Instructions[1])); // instruction reference will be changed later
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "not null"));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Call, mainMod.Import(typeof(Console).GetMethod("AddMessage", new Type[]{typeof(String)}))));
newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
newMethod.Body.Instructions [5].Operand = newMethod.Body.Instructions [8];

对结果说明的检查可以准确显示我的目标。然而他们没有工作。

这是我在程序中遇到的错误: InvalidProgramException:CommandLine中的IL代码无效:TestCecil():IL_0005:stloc.0

.Net Reflector会抛出一个错误,指出索引超出了数组的范围。

这使我认为第一条指令 Newobj 由于某种原因无法创建对象,也无法将引用推送到评估堆栈。然后,下一条指令 stloc.0 不能弹出它并将其放入局部变量列表中,这会引发错误。当我以相同的方式引用常规方法时,它们被称为正常,但构造函数会产生错误。我错过了什么?

1 个答案:

答案 0 :(得分:1)

Jb Evain 回答了关于Google群组的问题,所以我会在这里留下他的答案以防其他人遇到此问题。

  

您好,

     

我认为你只是缺少一件事:你不是在创造   变量

     

您需要将一个VariableDefinition添加到newMethod.Body.Variables。   否则stloc.0在索引0处没有变量。

相关问题