NASM和C互相调用对方的变量
hello.asm
global string
extern strhello
[section .data]
string:
db 'I am Chinese.',0x0A,0x0
[section .text]
global print_hello
global cpy_mem
print_hello:
mov edx, 13
mov ecx,[strhello]
mov ebx,1
mov eax,4
int 0x80
main.c
#include "stdio.h"
#include "string.h"
extern char *string;
extern void print_hello();
extern cpy_mem (void *dest, int len);
char *strhello = "Hello,world!\n";
char *str = NULL;
int
main ()
{
printf ("%x\n",&string);
str = &string;
printf ("%s", str);
print_hello ();
return 0;
}
编译方法:
nasm -f elf hello.asm -o hello.o
gcc -o main main.c hello.o
如果机器是64位的,nasm要用elf64编译。
nasm -f elf64 hello.asm -o hello.o
会创建一个叫main的可执行文件。
注意:
1.在C语言中定义了一个strhello的字符串变量,在C语言中strhello表示的是字符串的首地址,比如字符串的地址是0xa00001,而strhello是个指针即4字节其地址为0xb00001,
在C语言中strhello表示的值是 0xa00001
字符串的首地址,但到了NASM中则表示的 strhello变量的首地址了
0xb00001,所以mov ecx,[strhello]代码中加了中括号表示是内容,这一点一定要注意,否则会出错!!
2.第二点要注意的是,在NASM中定义了一个字符串string ,
在C语言中导入的话,就是表示字符串的首地址,因此要引用该字符串一定要取其地址,不要直接转为(char*)类型直接用,否则出错,这是因为直接转的话,就将字符串的前4个字节转成了字符串指针,但该指针是不确定会出现段错误!