2

Where exactly (CLR source file) can in find the actual implementation of the SomeDelegate.Invoke method?

How does the .Net runtime knows that calling SomeDelegate.Invoke should result in calling that implementation? Keep in mind that the SomeDelegate.Invoke method can have any number of arguments.

Ark-kun
  • 6,358
  • 2
  • 34
  • 70
  • As for how it's actually done, I'm not sure, but I found this: http://stackoverflow.com/questions/6388466/how-does-delegate-invoke-work – Ideae Aug 02 '14 at 14:03
  • Yes, I know about the existence `runtime` call. But I need the lower-level information. – Ark-kun Aug 02 '14 at 14:13
  • comdelegate.cpp is the start point, but you'll quickly get lost in the mountain of code that's underneath it. The "stub compiler" is a very non-trivial piece of code. – Hans Passant Aug 02 '14 at 14:29
  • @HansPassant Thanks. Looks like I found what I wanted: http://stackoverflow.com/a/25097048/1497385 I stumbled upon the comdelegate.cpp before, but I only saw the implementations of the `Delegate`/`MulticastDelegate` methods there and couldn't establish the link between the code there and custom delegates. – Ark-kun Aug 02 '14 at 16:22

1 Answers1

1

So, here is how the voodoo magic works (from what I found by glancing over the sources for an hour):

  1. At some time, the method table for the SomeDelegate class is populated and the runtime stumbles upon the Invoke method.
  2. The PreStubWorker (vm\prestub.cpp) is called, which calls DoPrestub, which calls MakeStubWorker
  3. The MakeStubWorker sees that the method is runtime-implemented (pMD->IsEEImpl), asserts that the method table (why ask the method table?) looks like a delegate and calls COMDelegate::GetInvokeMethodStub (vm\comdelegate.cpp) to create the stub.
  4. The COMDelegate::GetInvokeMethodStub method (vm\comdelegate.cpp) calls COMDelegate::TheDelegateInvokeStub which calls the EmitDelegateInvoke and EmitMulticastInvoke methods.
  5. The StubLinkerCPU::EmitDelegateInvoke and StubLinkerCPU::EmitMulticastInvoke methods are implemented in the vm\i386\stublinkerx86.cpp file (for x86) and vm\ppc\cgenppc.cpp (for PowerPC). These methods are quite short and emit the concrete assembly/CPU-specific implementations of the Invoke methods.
  6. The reference to the method implementation is put to the SomeDelegate's method table.
Ark-kun
  • 6,358
  • 2
  • 34
  • 70