Calling C Functions

An __asm block can call C functions, including C library routines. The following example calls the printf library routine:

#include <stdio.h>

char format[] = "%s %s\n";

char hello[] = "Hello";

char world[] = "world";

void main( void )

{

__asm

{

mov ax, offset world

push ax

mov ax, offset hello

push ax

mov ax, offset format

push ax

call printf

add sp, 6

}

}

Since function arguments are passed on the stack, you simply push the needed arguments—string pointers, in the example above—before calling the function. The arguments are pushed in reverse order, so they come off the stack in the desired order. To emulate the C statement

printf( format, hello, world );

the example pushes pointers to world, hello, and format, in that order, then calls printf. The last instruction in the __asm block adjusts the stack to account for the arguments previously pushed onto it.