Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve code from ILGenerator

I have write some function to create an exe file using ILGenerator. What I want is to show to user the IL language generated whithout using external tools like ILDasm or Reflector.

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

Important: I'm using Mono 2.6.

like image 217
carlesh Avatar asked Feb 22 '12 11:02

carlesh


2 Answers

If you have a MethodBuilder, you should be able to use builder.GetMethodBody().GetILAsByteArray() to get the IL as a byte[]. But to make any sense out of that, you would need to parse it somehow.

So, a better choice is probably using Mono Cecil, which can give you the IL code of an assembly in a readable format.

like image 194
svick Avatar answered Oct 06 '22 00:10

svick


As Hans Passant and svick had said, the answer is Mono.Cecil. Let's see:

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

Sure it can be done more efficient but it solves my problem.

like image 29
carlesh Avatar answered Oct 06 '22 00:10

carlesh