C语言的调用规约(Calling Convension)之参数传递和返回值

此文摘自 http://en.wikipedia.org/wiki/X86_calling_conventions 。

 

In these conventions the caller cleans the arguments from the stack, which allows for variable argument lists, eg. printf().

cdecl

The cdecl calling convention is used by many C systems for the x86 architecture. In cdecl, function parameters are pushed on the stack in a right-to-left order. Function return values are returned in the EAX register (except for floating point values, which are returned in the x87 register ST0). Registers EAX, ECX, and EDX are available for use in the function.

For instance, the following C code function prototype and function call:

int function_name(int, int, int);
 int a, b, c, x;
 ...
x = function_name(a, b, c);

will produce the following x86 Assembly code (written in MASM syntax, with destination first):

push c
push b
push a
call function_name
add esp, 12 ;Stack clearing
mov x, eax

The calling function cleans the stack after the function call returns.

There are some variations in the interpretation of cdecl, particularly in how to return values. As a result, x86 programs compiled for different operating system platforms and/or by different compilers can be incompatible, even if they both use the "cdecl" convention and do not call out to the underlying environment. Some compilers return simple data structures with the length of 2 registers or less in EAX:EDX, and larger structures and class objects requiring special treatment by the exception handler (e.g., a defined constructor, destructor, or assignment) are returned in memory. To pass "in memory", the caller allocates memory and passes a pointer to it as a hidden first parameter; the callee populates[vt. 填装] the memory and returns the pointer, popping the hidden pointer when returning.

posted @ 2010-09-14 08:32  lilei9110  阅读(733)  评论(0编辑  收藏  举报