微軟的 calling convention

__cdecl

預設使用的 calling convention。由呼叫者清除 stack,因此可以使用 vararg 的函式。然而因為呼叫者必需有清除 stack 的程式碼,因此產生出來的程式碼會比 __stdcall 還要大。

__stdcall

使用在 Win32 API 的函式。函式必需有 prototype 才能使用它。

__fastcall

使用 __fastcall 的函式,前兩個 DWORD 的參數(或更小)會放在 ECX 與 EDX 中(未來的 compiler 可能會放在不同的 register 中)。

__clrcall

它指定某個函式只能被 managed code 呼叫。它在下面兩種情況下可以增加效能:

1. 由 managed function 中呼叫 virtual managed function
2. 由 managed function 透過指標呼叫 managed function

__thiscall

預設被使用在無參數的 C++ 函式上。在 x86 上,this 指標會透過 ECX 傳遞而不是透過 stack。__thiscall 可以使用在預設為 __clrcall 的 member function 上,用來指定某個 member function 可以被 native code 呼叫。例:

struct CMyClass {
   void __thiscall mymethod();
   void __clrcall mymethod2();
};

mymethod2 只能被 managed code 呼叫,而 mymethod 可以被 native code 呼叫。

Calling Example: Function Prototype and Call  中列出使用 __cdecl/__stdcall/__fastcall 下,其 stack 及 regsiter 儲存的狀況。

Calling convention 就是說明了呼叫函式時,參數如何傳遞以及如何 return。使用不同的 calling convention 會產生出不同的 assembly code。在寫 C++ 時,我們不一定要了解,但如果程式中有連結 assembly code,那麼或許我們需要了解一些...

好文:

CodeProject: Calling Conventions Demystified
Calling Convention (呼叫慣例)


留言

熱門文章