Modify Function Pointer to Take Additional Parameters

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 19 14:07:25 PST 2016


On Fri, 19 Feb 2016 20:45:23 +0000, jmh530 wrote:

> I tried to use a cast (below) to modify the function pointer, but it is
> printing the second number instead of the first. I find this behavior
> strange...

If you want to cast function pointers successfully, you have to know the 
D calling convention.

See: https://dlang.org/spec/abi.html

Notably: "The last parameter is passed in EAX [a CPU register] rather 
than being pushed on the stack". So foo expected an argument in EAX, and 
it dealt with that. Calling foo_ pushes '1' onto the stack, sets EAX to 
'200', and then jumps to the function address.

(But note also: "The callee cleans the stack." So if you pass, say, a 
struct that has a destructor instead of an integer, that means the struct 
destructor won't be called. I was a little surprised that the stack 
pointer is correctly restored.)

If you had more arguments, you'd find similar results -- the last 
argument always goes to EAX, previous arguments are pushed on the stack 
in order, so you're always ignoring a prefix of the arguments. But it's a 
byte-wise prefix, so if you change the types, you'll see more significant 
changes.

Casting function pointers is "here be dragons" territory. Unfortunately, 
it's got the same syntax as routine stuff like integer truncation and 
class casts, so it looks deceptively safe.


More information about the Digitalmars-d-learn mailing list