Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating assembly code from C# code?

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#?

like image 597
dsta Avatar asked Feb 12 '12 07:02

dsta


Video Answer


2 Answers

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: enter image description here

like image 122
Maverick Meerkat Avatar answered Oct 10 '22 11:10

Maverick Meerkat


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.

like image 38
perelman Avatar answered Oct 10 '22 12:10

perelman