[英]Mono.Cecil: Log method's entry and exit point
我正在编写一个程序,可以将目标程序的IL更改为记录方法的入口和出口点。 我正在使用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:公共语言运行时检测到无效程序。 在CecilDemoTarget.Program.Main(String [] args)处的CecilDemoTarget.Target.Run()处。
我认为问题在于您在不指定this
情况下调用实例方法。
要解决此问题,您有两种选择:
LogEntry
static
。 this
通过将计算堆栈上ldarg.0
的前指令call
。 为了验证我所说的是正确的并在将来诊断出类似的问题,可以在修改后的程序集上运行Peverify。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.