2017-03-16 7 views
0

대상 메서드의 IL을 메서드의 진입 점과 종료점으로 변경할 수있는 프로그램을 작성하고 있습니다. 사용 중 Mono.Cecil 이 프로그램이 대상 메서드의 시작과 끝에 로그 문을 삽입하도록합니다.Mono.Cecil : 로그 메서드의 진입 점 및 종료점

샘플로 기본 프로그램을 사용해 보았습니다.

public class Target 
{ 
    // My target method. 
    public void Run() 
    { 
     Console.WriteLine("Run method body"); 
    } 

    // This is my log method, which i want to call in begining of Run() method. 
    public void LogEntry() 
    { 
     System.Console.WriteLine("******Entered in RUN method.***********"); 
    } 
} 

원본 프로그램.

public class Sample 
{ 
    private readonly string _targetFileName; 
    private readonly ModuleDefinition _module; 

    public ModuleDefinition TargetModule { get { return _module; } } 

    public Sample(string targetFileName) 
    { 
     _targetFileName = targetFileName; 

     // Read the module with default parameters 
     _module = ModuleDefinition.ReadModule(_targetFileName); 
    } 

    public void Run() 
    { 

     // Retrive the target class. 
     var targetType = _module.Types.Single(t => t.Name == "Target"); 

     // Retrieve the target method. 
     var runMethod = targetType.Methods.Single(m => m.Name == "Run"); 

     // Get a ILProcessor for the Run method 
     var processor = runMethod.Body.GetILProcessor(); 

     // get log entry method ref to create instruction 
     var logEntryMethodReference = targetType.Methods.Single(m => m.Name == "LogEntry"); 

     var newInstruction = processor.Create(OpCodes.Call, logEntryMethodReference); 

     var firstInstruction = runMethod.Body.Instructions[0]; 

     processor.InsertBefore(firstInstruction, newInstruction); 

     // Write the module with default parameters 
     _module.Write(_targetFileName); 
    } 
} 

나는 대상 프로그램, 나는 다음과 같은 오류 메시지가 무엇입니까의 IL을 변경할 내 소스 프로그램을 실행합니다.

System.InvalidProgramException : 공용 언어 런타임에서 잘못된 프로그램을 감지했습니다. at CecilDemoTarget.Target.Run() at CecilDemoTarget.Program.Main (String [] args).

답변

0

this을 지정하지 않고 인스턴스 메서드를 호출하는 것이 문제라고 생각합니다.

  • LogEntrystatic합니다

    는 두 가지 선택이,이 문제를 해결합니다.
  • call 앞에 ldarg.0 명령어를 추가하여 평가 스택에로드 을로드하십시오.

내가 말하는 말이 맞는지, 앞으로 유사한 문제를 진단하려면 수정 된 어셈블리에서 Peverify를 실행할 수 있습니다.

+0

완료. 고마워요 @ 스빅 – Krishnan