modifying. NET assemblies using Cecil

Source: Internet
Author: User
Tags emit git client

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 ();  
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.