2008-02-26

Calling Convention 呼叫慣例

1. 因為函式呼叫牽涉到參數的傳遞, 所以並是只是單純跳到那個Address執行程式碼再跳回來這麼簡單, 呼叫副程式(函式)的主程式, 需要知道怎麼填參數,副程式(函式)才能接到參數後進行處理, 再將結果, 傳給主程式, 所以這段協定, 稱之為Calling Convention(呼叫慣例)

但因為程式類型的不同(assambly, c/c++ , passcal ,fortran, vc .....), 並因為平台不同(Windows,Linux,MacOS,Unix...), 最主要的是CPU的不同(x86,PowerPC,Sparc.....), 所以這種協定就有很多方式


# What Are Calling Conventions?
C++ provides a way of defining a function and a way of calling that function with arguments that soon become second nature to use. When the function and calls to it are compiled there are quite a few different ways in which the process of getting those arguments to where the function’s code can “see” them before executing the code can be performed. There are pros and cons to each, and some compilers have extensions which allow you do choose which is used.

Most of the time there is no need to do anything other than use the defaults or, in a few cases where you are required to match a binary specification, do what you are told. But you might want to make use of this in some cases, or simply understand what it is going on with calling conventions used by code you interface with.

#
Normally you don't have to think about a function's calling convention: The compiler assumes __cdecl as default if you don't specify another convention. However if you want to know more, keep on reading ... The calling convention tells the compiler things like how to pass the arguments or how to generate the name of a function. Some examples for other calling conventions are __stdcall, __pascal and __fastcall. The calling convention belongs to a function's signature: Thus functions and function pointers with different calling convention are incompatible with each other! For Borland and Microsoft compilers you specify a specific calling convention between the return type and the function's or function pointer's name. For the GNU GCC you use the __attribute__ keyword: Write the function definition followed by the keyword __attribute__ and then state the calling convention in double parentheses. If someone knows more: Let me know;-) And if you want to know how function calls work under the hood you should take a look at the chapter Subprograms in Paul Carter's PC Assembly Tutorial.

Ref:
http://daydreamman.blogspot.com/2007/01/calling-convention.html
http://www.hackcraft.net/cpp/MSCallingConventions/
http://www.newty.de/fpt/fpt.html
http://tw.myblog.yahoo.com/hyper0672/article?mid=11&prev=12&next=10

--
怪~不太懂

No comments:

Post a Comment