撰寫函式,以內嵌組譯碼
Microsoft 專有的
如果您撰寫內嵌組譯程式碼的函式時,很容易將引數傳遞給函式,並從其傳回值。 下列範例會比較第一次寫為不同的組譯工具,而且並重寫內嵌組譯工具的函式。 呼叫的函式power2,會收到兩個參數,乘以 2 的乘冪第二個參數中的第一個參數。 寫入個別的組譯工具時,此函式可能會看起來如下:
; POWER.ASM
; Compute the power of an integer
;
PUBLIC _power2
_TEXT SEGMENT WORD PUBLIC 'CODE'
_power2 PROC
push ebp ; Save EBP
mov ebp, esp ; Move ESP into EBP so we can refer
; to arguments on the stack
mov eax, [ebp+4] ; Get first argument
mov ecx, [ebp+6] ; Get second argument
shl eax, cl ; EAX = EAX * ( 2 ^ CL )
pop ebp ; Restore EBP
ret ; Return with sum in EAX
_power2 ENDP
_TEXT ENDS
END
因為不同的組譯工具寫入它時,函數就會需要個別的原始程式檔和組件和連結步驟。 C 和 C++ 函式引數通常使用在堆疊上,所以此版本的power2函式存取它的引數,依其在堆疊上的位置。 (請注意, 模型指示詞,適用於 MASM 和一些其他的組合,也可讓您依名稱存取堆疊引數] 和 [本機堆疊變數。)
範例
此程式會將power2與內嵌組譯程式碼的函式:
// Power2_inline_asm.c
// compile with: /EHsc
// processor: x86
#include <stdio.h>
int power2( int num, int power );
int main( void )
{
printf_s( "3 times 2 to the power of 5 is %d\n", \
power2( 3, 5) );
}
int power2( int num, int power )
{
__asm
{
mov eax, num ; Get first argument
mov ecx, power ; Get second argument
shl eax, cl ; EAX = EAX * ( 2 to the power of CL )
}
// Return with result in EAX
}
內嵌版本power2函式會依名稱參照它的引數,並會出現在相同的原始程式檔與其他程式。 這個版本也會需要較少的組件的指令。
因為內嵌版本power2不會執行 c return陳述式,它會無害的警告如果您編譯在警告層級 2 或更高。 此函式會傳回一個值,但編譯器無法確定,在沒有return陳述式。 您可以使用 # pragma 警告來停用這項警告的產生。
結束 Microsoft 特定