Saturday, 16 March 2013

Calling conventions in C/C++

There are following five calling conventions used in C/C++:-
1)_cdecl
2)_clrcall
3)_stdcall
4)_fastcall
5)_thiscall

1)_cdecl:-_cdecl is the default calling convention in C/C++.In this calling convention the stack is cleaned up by the caller .It creates larger executable than _stdcall because it requires each function call to include stack cleanup code .It pushes parameters on the stack in reverse order means right to left.There is no case translation performed in this calling convention.Underscore caracter(_) is used as prefix to names ,except when exporting _cdecl functions that use C linkage .

2)_clrcall:- _clrcall is used for all virtual function which only be called from managed code .This calling convention can not be used for function that will be called from native code.It improves performance in the case of virtual functions.The load parameters onto CLR expression stack in left to right order.When a function is declared with _clrcall ,code will generated when needed for example ,when function is called.

3) _stdcall:-_stdcall calling convention is used to call Win32 API functions .In this calling convention callee
cleans the stack ,so the compiler makes vararg functions _cdecl .Functions that uses this calling convention require a function prototype .It pushes parametes on the stack in reverse order means right to left .Function declared  using with the _stdcall modifier returns values the same way as function declare using _cdecl.

4)_fastcall:-It specifies that arguments to functions are to be passed in registers ,when possible.Stack clean up is done by callee function .It pushes parameters in reverse order means right to left.There is no case translation is performed in this calling convention.

5)_thiscall:-This is used on member functions and  it is the default calling convention used by C++ member functions that do not use variable arguments .In this calling convention the callee cleans the stack which is impossible for vararg functions.The arguments are pushed on stack from right to left .On reason to use _thiscall is in classes whose member functions use _clrcall by default .In that case we can use _thiscall to make individual member function callable from native code .

We can easily seen their characteristic from following table:-

No comments:

Post a Comment