implicitly convert function pointers to delegates

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Oct 26 12:18:50 PDT 2008


KennyTM~ wrote:
> Jarrett Billingsley wrote:
>> On Sun, Oct 26, 2008 at 2:11 PM, KennyTM~ <kennytm at gmail.com> wrote:
>>> BTW,
>>>
>>>  alias float delegate (in float) DG;
>>>
>>>  float area (in float radius) {
>>>        float r2 = radius * radius;
>>>        return 3.1415926535 * radius;
>>>  }
>>>
>>>  DG x;
>>>  x.ptr = null;
>>>  x.funcptr = &area;
>>>  // writefln(typeof(x.funcptr).stringof); // ensure it's an FP not DG.
>>>  writefln(x(10)); // writes 314.159 without any error.
>>>
>>>
>>> Why this simpler solution is not used? The function pointer can't 
>>> touch the
>>> frame pointer anyway (an FP cannot access stuff outside its scope).
>>>
>>
>> The calling conventions for functions and delegates is different.
>> This method does not work in the general case.
> 
> I see. And indeed it does not work if I change float to int -- the 
> arguments are shifted by 4 bytes to the left. (How come float works??)

Floats are passed differently.

For instance, DMD will put the first argument into EAX if it's an int or 
pointer (including x.ptr in your code), while it passes floats on the stack.
My x86-64 GDC passes a float in a floating-point register, while ints 
and pointers go into general-purpose registers (until it runs out of 
appropriate registers for that function call, anyway).

So on both compilers floats will "work" because they're not moved 
elsewhere by an extra pointer at the front of the parameter list (which 
is essentially what happens when you call a function through a 
delegate's function pointer) while passing in an extra null means the 
first int an unsuspecting function reads is 0.



More information about the Digitalmars-d mailing list