_cdecl与_stdcall区别

一、概念

(1)_stdcall调用

_stdcall是Pascal程序的缺省调用方式,参数采用从右到左的压栈方式,由调用者完成压栈操作,被调函数自身在返回前清空堆栈
WIN32 Api都采用_stdcall调用方式

对于如下函数:

/* 1. calling function in C++ */
i = Function(x, y, z);

/* 2. function body in C++ */
int Function(int a, int b, int c) { return a + b + c; }

STDCALL调用过程如下

/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable

/* 2. STDCALL 'Function' body in pseaudo-assembler */
pop 'a' from stack to register A
pop 'b' from stack to register B
add A and B, store result in A
pop 'c' from stack to register B
add A and B, store result in A
jump back to caller code (a, b and c are no more on the stack, result in register A)

(2)_cdecl调用

_cdecl是C/C++的缺省调用方式,参数采用从右到左的压栈方式,由调用者完成压栈操作 ,并且由调用者完成清栈工作

前述函数在CDECL惯例下调用过程如下:

/* 1. calling CDECL 'Function' in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call (jump to function body, after function is finished it will jump back here, the address where to jump back is in registers)
move contents of register A to 'i' variable
pop all from the stack that we have pushed (copy of x, y and z)

/* 2. CDECL 'Function' body in pseaudo-assembler */
/* Now copies push onto the stack are 'a', 'b' and 'c' variables */
copy 'a' (from stack) to register A
copy 'b' (from stack) to register B
add A and B, store result in A
copy 'c' (from stack) to register B
add A and B, store result in A
jump back to caller code (a, b and c still on the stack, result in register A)

二、特性

cdecl与stdcall的调用过程不同,使得二者有以下不同特性:

(1)代码量不同

_stdcall生成代码量小于_cdecl,因为如果使用_cdecl的函数多次调用同一函数,就要产生多份恢复码。

(2)功能不同

_cdecl可实现变长参数列表的函数
由于被掉函数不知道自己实际运行时的参数长度,因此需要调用者来恢复栈。

(3)使用范围

_stdcall:通常用于DLL的创建(以支持多语言调用);此外Win32 API函数皆用_stdcall(比如MessageBox),所以Win32程序中的自定义函数也做好使用_stdcall。
_cdecl:非DLL的console程序。

参考资料

[1]函数调用的区别:_cdecl以及_stdcall
[2]stdcall and cdecl

猜你喜欢

转载自blog.csdn.net/werweqg/article/details/44877285