Search code examples
c#delegatesdecompiling

__methodptr in decompiled C# code


I'm using dotPeek to dive deeper into the C# compiler magic, and something in decompiled code caught my attention. I'm creating an Action<int> instance and pass it to Start() method, the compiler generates the following:

new Program().Start(new Action<int>((object) cDisplayClass1, __methodptr(<Main>b__0)));

I generally understand what's happening here, my only question is what is __methodptr? To be exact, where does it come from? Is it from IL? dotPeek doesn't know a thing about it or the assembly containing it. Google doesn't give a precise answer either, only the same snippets of code with no explanations whatsoever.

Thank you!


Solution

  • the __methodptr corresponds to IL instruction ldftn, roughly speaking ldftn load "function pointer" onto evaluation stack. here is a sample:

    the de-compiled source:

       private static void Main(string[] args)
        {
          Program.\u003C\u003Ec__DisplayClass0_0 cDisplayClass00 = new Program.\u003C\u003Ec__DisplayClass0_0();
          cDisplayClass00.xx = 100;
          // ISSUE: method pointer
          new Action((object) cDisplayClass00, __methodptr(\u003CMain\u003Eb__0))();
          Console.WriteLine(cDisplayClass00.xx);
        }
    

    the IL:

    1 load function pointer class::method

    IL_000f: ldloc.0      // cDisplayClass00
    IL_0010: ldftn        instance void TestIL.Program/'<>c__DisplayClass0_0'::'<Main>b__0'()
    

    2 new a delegate passing object and function pointer

    IL_0016: newobj       instance void [mscorlib]System.Action::.ctor(object, native int)
    IL_001b: stloc.1      // V_1
    

    3 call the delegate

    IL_001c: ldloc.1      // V_1
    IL_001d: callvirt     instance void [mscorlib]System.Action::Invoke()
    IL_0022: nop