Where exactly is SomeDelegate.Invoke implemented a

2019-07-20 15:04发布

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.

标签: c# delegates clr
1条回答
爷的心禁止访问
2楼-- · 2019-07-20 15:58

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.
查看更多
登录 后发表回答