C ++ resentment Note 3-function call conventions
Function call conventions refer to the Conventions on the parameter stack pressure sequence and stack position. This Convention is specified during function declaration, for example:
Void _ stdcall FN (INT arg1, int arg2 );
Among them, _ stdcall is the call Convention, indicating that the parameters are from right to left in the stack, and the function itself is responsible for parameter stack play.
Another common convention is _ cdecl, which indicates that the parameter is from right to left, and the function caller is responsible for parameter stack play.
If no call convention is specified, the compiler uses the default convention. In vs, the default conventions can be set in project properties:
In VC ++, common functions use the _ cdecl convention, but class member functions, including constructors, use the _ stdcall Convention (I don't know why ), we can see from their disassembly code.
Source code:
class Node{public:Node(){}void Fn( int a, int b ){}};void Fn(int a, int b){}void main(){Node n;n.Fn(1, 2);Fn( 1, 2);}
The main and FN disassembly code is as follows:
Bytes -------------------------------------------------------------------------------------------------------------------
In assembly, the difference between function call conventions is huge, but in advanced languages, it is seldom seen. The following is an example of program crash caused by inconsistent conventions. The program must be compiled in the debug version or marked with/OD in the release version to prohibit optimization. Otherwise, the program may not crash.
Typedef void (_ cdecl * cdecltype) (void *); void _ stdcall FN (void * P) {} void mycallback (cdecltype PFn) {PFN (0 ); /* the PFN parameter will be shot twice. If the stack balance is broken, mycallback will not find the return address */} void main () {mycallback (cdecltype) FN );}