If you write a function
with inline assembly code, its easy to pass arguments to
the function and return a value from it. The following examples
compare a function first written for a separate assembler and
then rewritten for the inline assembler. The function, called
power2, receives two parameters, multiplying the
first parameter by 2 to the power of the second parameter. Written
for a separate assembler, the function might look like this:
; POWER.ASM; Compute the power of an integer;PUBLIC _power2_TEXT SEGMENT WORD PUBLIC 'CODE'_power2 PROCpush ebp ; Save EBPmov ebp, esp ; Move ESP into EBP so we can refer; to arguments on the stackmov eax, [ebp+4] ; Get first argumentmov ecx, [ebp+6] ; Get second argumentshl eax, cl ; EAX = EAX * ( 2 ^ CL )pop ebp ; Restore EBPret ; Return with sum in EAX_power2 ENDP_TEXT ENDSEND
Since its written
for a separate assembler, the function requires a separate source
file and assembly and link steps. C and C++ function arguments
are usually passed on the stack, so this version of the power2
function accesses its arguments by their positions on the stack.
(Note that the MODEL directive, available in MASM and some
other assemblers, also allows you to access stack arguments and
local stack variables by name.)
The POWER2.C program writes
the power2 function with inline assembly code:
/* POWER2.C
*/
#include <stdio.h>int power2( int num, int power );void main( void ) {printf( "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 argumentmov ecx, power ; Get second argumentshl eax, cl ; EAX = EAX * ( 2 to the power of CL )}/* Return with result in EAX */}
The inline version of the
power2 function refers to its arguments by name and
appears in the same source file as the rest of the program. This
version also requires fewer assembly instructions.
Because the inline version
of power2 doesnt execute a C return
statement, it causes a harmless warning if you compile at warning
level 2 or higher. The function does return a value, but the compiler
cannot tell that in the absence of a return statement.
You can use #pragma warning to disable the generation of this
warning.
Shamelessly grepped
from MSDN
Last Updated by Jeff, 04-29-2000