C ++ resentment Note 3-function call conventions

Source: Internet
Author: User

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 );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.