问题
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.
回答1:
So, here is how the voodoo magic works (from what I found by glancing over the sources for an hour):
- At some time, the method table for the
SomeDelegateclass is populated and the runtime stumbles upon theInvokemethod. - The
PreStubWorker(vm\prestub.cpp) is called, which callsDoPrestub, which callsMakeStubWorker - The
MakeStubWorkersees that the method is runtime-implemented (pMD->IsEEImpl), asserts that the method table (why ask the method table?) looks like a delegate and callsCOMDelegate::GetInvokeMethodStub(vm\comdelegate.cpp) to create the stub. - The
COMDelegate::GetInvokeMethodStubmethod (vm\comdelegate.cpp) callsCOMDelegate::TheDelegateInvokeStubwhich calls theEmitDelegateInvokeandEmitMulticastInvokemethods. - The
StubLinkerCPU::EmitDelegateInvokeandStubLinkerCPU::EmitMulticastInvokemethods are implemented in thevm\i386\stublinkerx86.cppfile (for x86) andvm\ppc\cgenppc.cpp(for PowerPC). These methods are quite short and emit the concrete assembly/CPU-specific implementations of theInvokemethods. - The reference to the method implementation is put to the
SomeDelegate's method table.
来源:https://stackoverflow.com/questions/25095709/where-exactly-is-somedelegate-invoke-implemented-and-how-is-it-wired-to-the-de