Friday, August 29, 2014

WINAPI Keyword

Wonder whether to add "WINAPI" keyword in a function prototype or not? Here is the main differences:

Specifying WINAPI indicates the __stdcall calling convention; not specifying WINAPI indicates the __cdecl calling convention by default (unless you have set the default calling convention to __stdcall via project settings).

Low-level wise, these calling conventions indicate how parameters are pushed onto the stack when the function is called and indicate whether the calling function or the called function performs stack cleanup.

A unique feature of the __cdecl calling convention is that for such functions, variable argument lists can be used, e.g. :

int __cdecl MyFuntion(int i, ...);

and client code can be written as follows :

int i = MyFuntion(4, 1, 2, 3, 4);

int j = MyFunction(2, 5, 100);

This is not possible for __stdcall functions.

Now because a variable number of arguments can be passed into such a function, only the caller code (i.e. client code) will know how many parameters were actually passed to the function. Hence it is the caller that is responsible to perform stack cleanup. This can result in a larger overall code size because each call to a __cdecl function requires stack cleanup code.

For a __stdcall function, the number of parameters are fixed always and so the called function can perform the stack cleanup operation. This saves code space because cleanup code need be emitted only once for each __sdcall function.

For more information on calling conventions, pls refer to :

Argument Passing and Naming Conventions
http://msdn.microsoft.com/en-us/library/984x0h58(VS.71).aspx

Note that for a function to be exported, it does not have to be specified as WINAPI (i.e. __stdcall). It can also be specified as __cdecl.