Programmatic CIL Access for .NET Type

Is there a straighforward library that I can use to access CIL for a .NET type? Let me demonstrate that I want a dummy CilExtractor:

[Serializable]
public class Type_For_Extract_Cil_Test {

  private int _field = 3;

  public int Method(int value) {
    checked {
      return _field + value;
    }
  }

}

[Test]
public void Extract_Cil_For_Type_Test() {
  string actualCil = CilExtractor.ExtractCil(typeof(Type_For_Extract_Cil_Test));
  string expectedCil = @"
    .class public auto ansi serializable beforefieldinit Type_For_Extract_Cil_Test
      extends [mscorlib]System.Object
    {
      .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
      {
        .maxstack 8
        ldarg.0 
        ldc.i4.3 
        stfld int32 Type_For_Extract_Cil_Test::_field
        ldarg.0 
        call instance void [mscorlib]System.Object::.ctor()
        ret 
      }

      .method public hidebysig instance int32 Method(int32 'value') cil managed
      {
        .maxstack 8
        ldarg.0 
        ldfld int32 Type_For_Extract_Cil_Test::_field
        ldarg.1 
        add.ovf 
        ret 
      }

      .field private int32 _field
    }";
  // indentations and code formatting issues apart, this should succeed
  Assert.AreEqual(expectedCil, actualCil);
}

I know that I can do this with Mono.Cecil or Reflector, but I also know that it takes a lot of code to write. Since Reflector already does this in its user interface, is there a simple way to access this function, for example, by simply calling a method? Are there other libraries that are better suited for this particular scenario?

+3
source share
2 answers

ildasm.exe, .NET, , .

​​ MSDN .

+3

, ildasm.

, Mono.Cecil , CIL. , .

, Reflection.Emit CIL, .

+1

Source: https://habr.com/ru/post/1744187/


All Articles