Re: [GD-General] variadic functions
Brought to you by:
vexxed72
From: Andras B. <bn...@ma...> - 2003-11-27 08:42:58
|
Hi Brett, > The compiler strips the "..." off the back and makes a normal function > out of the variadic one, and the preceeding four functions are then used > to access these unknown parameters. The start function takes the last > known parameter as a value so at first glance it seems the function > knows how many paramters there are because because it can compare the > last known argument with the value on the stack. The problem is that > since the parameters were pushed in reverse order how would it know how > many parameters there are? If it were in direct order, you could take > the stack pointer minus the stack pointer at the last parameter position > (which is provided) and the diffference would be the number of > arguments. But since they are reversed how does the va_arg function > know when to stop? The answer is simple: It does not know! :( That's exactly why vararg functions always use the cdecl calling convention. This requires that the caller cleans the stack, because the caller always knows the number of params on the stack, while the calle doesn't (in the case of vararg). Think of printf! The first param is supposed to be a pointer to a format string. Reading that string printf determines how many (and of what type) values it has to read from the stack. I'm pretty sure that every one of us crashes a program every once in a while because of unmatching params and format string. The reason for this is that there is just no way printf can verify the stuff you gave is valid. > Has anybody else run into this before? How did you solve it? Well, you could use a format string like printf, or something similar. If you do this for scripting, then your script binding engine knows all the params, so it might be a good idea to generate the format description string automatically. This way the script writers could call the function with any number of params without explicitly describing their type and number in a format string. The ultimate solution would be of course the introduction of a new calling convention, but I don't really know who's responsibility is this... anyone? :) Andras |