Skip to content

Instantly share code, notes, and snippets.

@philiplaureano
Created May 8, 2011 07:03
Show Gist options
  • Save philiplaureano/961185 to your computer and use it in GitHub Desktop.
Save philiplaureano/961185 to your computer and use it in GitHub Desktop.
protected override void ModifyTargetMethod(MethodDefinition targetMethod)
{
// In this example, we are going to redirect all Console.WriteLine calls
// to the FakeConsole.WriteLine() method
var module = targetMethod.Module;
var body = targetMethod.Body;
// In order to use FakeConsole.WriteLine(), we need to use Cecil to "import"
// the method into the modified assembly's module
var writeLine = module.Import(typeof (FakeConsole).GetMethod("WriteLine"));
var callInstructions = (from instruction in body.Instructions
where instruction.OpCode == OpCodes.Call
select instruction).ToArray();
foreach(var instruction in callInstructions)
{
// Notice how replacing the old method with the FakeConsole.WriteLine() method
// redirects all console calls to the FakeConsole class
instruction.Operand = writeLine;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment