Cannot implicitly convert delegate to function

Don Clugston dac at nospam.com.au
Fri Apr 28 03:03:51 PDT 2006


Lionello Lunesu wrote:
> BCS wrote:
>> In article <e2qlrk$1uh5$1 at digitaldaemon.com>, Jarrett Billingsley says...
>>> "Lionello Lunesu" <lio at lunesu.remove.com> wrote in message 
>>> news:e2qig4$1ovk$1 at digitaldaemon.com...
>>>> Hi,
>>>>
>>>> Shouldn't a (pointer to a) function be convertible to a delegate? 
>>>> Seems to me it's like casting an int to a long; the latter has "more 
>>>> info" and can be converted back into the former without the loss of 
>>>> data. The same holds for function/delegate: a function could be 
>>>> converted to a delegate for "null"; by forgetting the "this" (null), 
>>>> we get the function pointer back.
>>> Without the context pointer, a delegate cannot function properly.  So 
>>> casting from delegate to function isn't really possible.
>>>
>>> The other way around.. I don't think so either.  Something tells me 
>>> the mechanism for a delegate call would screw up if the context 
>>> pointer were null, or if the function weren't designed to be a delegate.
>>>
>>
>> It would take some ASM hacking but It might be possible to place the 
>> fn ptr in
>> the context pointer and have the delegate's function rearrange the 
>> stack and
>> then call (with tail recursion) the function.
> 
> Isn't "this" basically a hidden parameter? A delegate would be a "this" 
> together with a function pointer. Upon calling it would first load/push 
> the hidden parameter before the call to the function.
> 
> The question then is: does "this" interfere with a function's parameter?
> 
> If, like in the MSVC case, "this" is always loaded into register ecx, it 
> would just work: ecx would get "null" and the function gets called with 
> the usual parameters. Since the function does not access [ecx] (it's a 
> function, not a member of any class) the null would not interfere.

This is exactly right. Whether or not a function can be trivially 
converted to a delegate depends on the calling conventions used by the 
compiler.

For the gory details, see my article
http://www.codeproject.com/cpp/FastDelegate.asp
which covers C++ member functions and delegates in more detail than 
anything else on the planet, and shows how ugly things become when a 
language doesn't define its ABI properly.

-Don.



More information about the Digitalmars-d-learn mailing list