Generating assembly code from C# code?

后端 未结 4 1641
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 06:41

Is there any way to generate assembly code from C# code? I know that it is possible with C code with GAS, but does anybody know if it\'s possible with C#?

相关标签:
4条回答
  • 2020-12-19 06:57

    C# code compiles into MSIL (MS Intermediate Language) which is actually not really asm-code you get from C compiler. Read more about about how .NET Framework applications run.

    If you want to look at generated IL code see this question.

    0 讨论(0)
  • 2020-12-19 07:03

    You can do this in a bit of an indirect way using the NGEN tool and then disassemble the binary that is produced. Alternatively you can use a debugger to inspect the JIT code created from the MSIL, Ollydbg 2 is one such debugger able to do this.

    0 讨论(0)
  • 2020-12-19 07:08

    You can use BenchmarkDotNet with the printAsm flag set to true.

    [DisassemblyDiagnoser(printAsm: true, printSource: true)] // !!! use the new diagnoser!!
    [RyuJitX64Job]
    public class Simple
    {
        int[] field = Enumerable.Range(0, 100).ToArray();
    
        [Benchmark]
        public int SumLocal()
        {
            var local = field; // we use local variable that points to the field
    
            int sum = 0;
            for (int i = 0; i < local.Length; i++)
                sum += local[i];
    
            return sum;
        }
    
        [Benchmark]
        public int SumField()
        {
            int sum = 0;
            for (int i = 0; i < field.Length; i++)
                sum += field[i];
    
            return sum;
        }
    }
    

    Which produces:

    0 讨论(0)
  • 2020-12-19 07:10

    C# is normally compiled to the .NET bytecode (called CIL or MSIL) and then JIT ("Just In Time") compiled to native code when the program is actually run. There exist ahead of time compilers for C# like Mono's AOT, so you could possibly compile a C# program through one of those and then disassemble it. The result is likely to be very difficult to follow.

    More likely, you may want to look at the bytecodes which are somewhat higher level than a CPU's assembly code, which you can do by using ILdasm on a compiled .exe of a C# program.

    0 讨论(0)
提交回复
热议问题