Mix ANSI C & Asm
Part-2
Using MS C/C++
& MASM
1.1 Machine environment
32-bit Microsoft Windows 2000 Professional U.S Edition
1.2 Microsoft C/C++ compiler
Microsoft Visual Studio 2005 Team Edition, cl Version 14.0
Include /Gd /TC compiler options.
1.3 Microsoft MASM compiler
Microsoft Visual Studio 2005 Team Edition, ml Version 8.0
Include /c /nologo /Fo compiler options.
Illustrate how to call the routine write in MASM from ANSI C.
2.1 List of c & asm files
2.2 Source code
2.2.1 main.c
#include "asmlib.h"
int main(argc, argv)
int argc;
char** argv;
{
int x = 100, y = 101, ret;
ret = a_byval(x, y);
a_byref(&x, &y);
return 0;
}
2.2.2 asmlib.asm
.386
.model flat, c
.code
a_byval proc x: dword, y: dword
mov eax, x
add eax, y
ret
a_byval endp
a_byref proc x: dword, y: dword
push eax
push ecx
mov eax, x;
mov ecx, y;
inc dword ptr [eax]
inc dword ptr [ecx]
pop ecx
pop eax
ret
a_byref endp
end
2.2.3 asmlib.h
/*
ASSEMBLY ROUTINES PROTOTYPE
You can call it from C
*/
int a_byval(int, int);
int a_byref(int*, int*);
Illustrate how to call the routine write in ANSI C from MASM.
3.1 List of c & asm files
3.2 Source code
3.2.1 main.c
#include <stdlib.h>
#include "asmlib.h"
int main(argc, argv)
int argc;
char** argv;
{
c_struct_1 c1, c2;
a_printf();
c1 = a_check();
c2.fld_char = c1.fld_char;
c2.fld_uint = c1.fld_uint;
return 0;
}
3.2.2 asmlib.asm
.386
.model flat, c
include asmlib.inc
.data
_msg db "Hello, World!", 0
_fmt db "%s", 0
.code
a_printf proc
push offset _msg
push offset _fmt
call printf
add esp, 8
ret
a_printf endp
a_check proc
call c_check
inc edx
sub eax, 2
ret
a_check endp
end
3.2.3 asmlib.inc
printf proto
c_check proto
3.2.4 asmlib.h
#include <stdio.h>
typedef struct c_struct_1 {
char fld_char;
int fld_uint;
} c_struct_1;
/*
ASSEMBLY ROUTINES PROTOTYPE
You can call it from C
*/
int a_printf(void);
c_struct_1 a_check(void);
/*
Return the struct will be treat as long long (2*32)
the 'fld_char' field be align to 32-bits.
----------------------
|edx | fld_char |
|---------------------
|eax | fld_uint |
----------------------
*/
c_struct_1 c_check(void) {
c_struct_1 ret = {'C', 30};
return ret;
}