Cecil is a subproject of Mono that is used to read and write an assembly and is already used for Mono debugging, and is used by Reflector as the underlying library. Recently put dbentry use Emit to generate the assembly of the way, changed to use Cecil way, in my experience, Cecil is relatively excellent, there are some places, more comfortable than the use of Emit, but some places are more cumbersome.
I'm using the latest version of Git, and if you want to test it, it's also recommended to use Git, so you need to install a git client.
Here, use a very simple example to illustrate the basic usage of Cecil.
First, we write a test assembly TestApp.exe:
using System;
namespace TestApp
{
class Program
{
static void Main()
{
Console.WriteLine("Main");
}
private static void Before()
{
Console.WriteLine("Before");
}
private static void After()
{
Console.WriteLine("After");
}
}
}
Then, write an application CecilTest.exe that uses Cecil for rewriting:
using System;
using System.Linq;
using Mono.cecil;
using Mono.Cecil.Cil;
Namespace Ceciltest
{
Class program
{
static void Main (string[] args)
{
if (args). Length!= 1)
{
Console.WriteLine ("Usage:ceciltest TestApp.exe");
var m = moduledefinition.readmodule (Args[0]);
var prog = M.types.first (p => p.name = = "program");
var main = Prog. Methods.first (p => p.name = = "Main");
var before = Prog. Methods.first (p => p.name = = "before");
var after = Prog. Methods.first (p => p.name = "after");
var il = main. Body.getilprocessor ();
IL. InsertBefore (Main. Body.instructions[0], IL. Create (Opcodes.call, before));
IL. InsertBefore (Main. Body.Instructions.Last (), IL. Create (Opcodes.call, after));
M.write (Args[0] + ". exe");
Console.WriteLine ("Done");
Console.ReadLine ();
}
}