Get code from ILGenerator

I wrote some function to create an exe file using ILGenerator. I want to show the user the IL language, created without using external tools such as ILDasm or Reflector.

during the execution of my program, I added each OpCode to ILGenerator, so I can save each of this OpCode in a list using a string with the OpCode view, but I would prefer to get the IL code directly. It can be done?

It is important . I am using Mono 2.6.

+5
source share
2 answers

As Hans Passant and svick said , Mono.Cecil answer. Let's get a look:

using Mono.Cecil;
using Mono.Cecil.Cil;

[...]


public void Print( ) {
    AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly( this.module_name );

    int i = 0, j = 0;
    foreach ( TypeDefinition t in assembly.MainModule.Types ) {
        if ( t.Name  == "FooClass" ) {
            j = i;
        }
        i++;
    }

    TypeDefinition type = assembly.MainModule.Types[ j ];

    i = j = 0;
    foreach ( MethodDefinition md in type.Methods ) {
        if ( md.Name == "BarMethod" ) {
            j = i;
        }
        i++;
    }

    MethodDefinition foundMethod = type.Methods[ j ];

    foreach( Instruction instr in foundMethod.Body.Instructions ) {
        System.Console.WriteLine( "{0} {1} {2}", instr.Offset, instr.OpCode, instr.Operand );
    }
}

, , .

+3

MethodBuilder, builder.GetMethodBody().GetILAsByteArray(), IL byte[]. , - .

, , , Mono Cecil, IL .

+5

All Articles