- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 329字
- 2021-06-10 18:28:06
Specifying how the stack Is maintained
Visual C++ supports six calling conventions that you can use on a function. The __clrcall specifier means that the function should be called as a .NET function and allows you to write code that has mixed native code and managed code. C++/CLR (Microsoft's language extensions to C++ to write .NET code) is beyond the scope of this book. The other five are used to indicate how parameters are passed to a function (on the stack or using CPU registers) and whose responsibility it is to maintain the stack. We will cover just three: __cdecl, __stdcall, and __thiscall.
You will rarely explicitly use __thiscall; it is the calling convention used for functions defined as members of custom types, and indicates that the function has a hidden parameter that is a pointer to the object that can be accessed through the this keyword in the function. More details will be given in the next chapter, but it is important to realize that such member functions have a different calling convention, especially when you need to initialize function pointers.
By default, C++ global functions will use the __cdecl calling convention. The stack is maintained by the calling code, so in the calling code each call to a __cdecl function is followed by code to clean up the stack. This makes each function call a little larger, but it is needed for variable argument lists to be used. The __stdcall calling convention is used by most of the Windows SDK functions and it indicates that the called function cleans up the stack so there is no need for such code to be generated in the calling code. Clearly, it is important that the compiler knows that a function uses __stdcall because, otherwise, it will generate code to clean up a stack frame that has already been cleaned up by the function. You will usually see Windows functions marked with WINAPI, which is a typedef for __stdcall.