When and how do I use the Ldvirtftn opcode?

You could try making the following changes to understand what’s going on.

Here is what happens in the ldftn case. Your method creates a delegate that has: no first argument (usually used only for static methods); Base.Method() as the method (which is not static). You create this delegate as Action, which happens to have one parameter.

When you call this delegate in this line: func()(new Child()); the CLR uses the new Child instance as the “first argument�. Since the method you are calling is not static, the first argument becomes the this pointer. Thus, this call becomes equivalent to new Child().Method(); and this causes a separate virtual-method dispatch at invoke time (not at ldftn time), so Child.Method() gets called.

This is why it prints “Child� Instead of the “Base� That you probably expected.

In the ldvirtftn case, you are getting an invalid program because you forgot that ldvirtftn requires an object reference on the stack while ldftn doesn’t. You could try making the following changes to understand what’s going on: Instead of null, pass an actual instance of Base or Child to the delegate constructor, as is customary for non-static methods. You will find that it will then refuse to create the delegate because the number of parameters no longer match (Action requires one parameter, but Method() has none).

Make the number of parameters match, either by changing Action to simply Action, or by making Method() accept a parameter. In both cases, you will probably quickly find that it does what you expect.In particular, you will find that the delegate created with ldftn will always call Base.Method() even if you created it with an instance of Child.

Actually the virtual dispatch was what I was after. I didn't know virtftn only worked while passing an instance, so am I suppose to send to go: ld instance,dup,ldvirtftn Method,newobj delegate ctor? – Michael B Dec 16 '10 at 13:50.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions