2014-11-23 3 views
2

클래스에 빈 메소드를 삽입했습니다. 지금이 간단한 다음 코드를 채우기 위해 노력하고있어 :Mono.Cecil - 생성자를 가져올 수 없습니다.

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

나는 Reflexil와 ILCode에이 조각을 변환 한 내가 Reflexil 자체를 주입 할 때 잘 작동합니다.

그러나 Cecil과 동일한 ilcode 명령어를 삽입하면 프로그램을 실행할 때 오류가 발생하며 .NET Reflector에서도 열 수 없습니다. 내가 어떻게

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 

이있다 : 이것은 내가 주입하고있어 ILcode입니다

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 : 명령 행에 잘못된 IL 코드 : 여기

내가 프로그램에서 얻을 오류입니다 TestCecil()는 : IL_0005 : stloc.0

그리고 닷넷 리플렉터 인덱스가 범위를 벗어난라는 오류가 발생합니다 배열의.

어떤 이유로 든 첫 번째 명령 Newobj이 개체를 만들 수 없으며 참조를 평가 스택으로 푸시하지 않는다고 생각합니다. 그런 다음 다음 명령 stloc.0은이를 팝하여 로컬 변수 목록에 넣을 수 없으며 오류가 발생합니다. 같은 방법으로 일반적인 메서드를 참조 할 때 이들은 정상적으로 호출되지만 생성자는 오류를 생성합니다. 내가 놓친 게 무엇입니까?

답변

1

Jb Evain이 Google 그룹의 질문에 답변 했으므로 다른 사람이이 문제를 가지고있는 경우를 대비하여 여기에 답글을 남깁니다.

안녕,

난 당신이 한 가지를 놓치고 생각 : 당신이 변수를 만들 아닙니다.

newMethod.Body.Variables에 VariableDefinition을 추가해야합니다. 그렇지 않으면 stloc.0은 인덱스 0에 변수가 없습니다.

관련 문제