Pass an argument from C to assembly?
How can I pass an argument from a C main function to an a开发者_StackOverflow社区ssembly function? I know that my custom function has to look something like:
void function(char *somedata) __attribute__((cdecl));
Now how would I use somedata
in an assembly file. My operation system is Linux Ubuntu and my processor is x86.
I'm a bit of a noob at this but hopefully this example will get you on your way. I've tested it and it works, the only issue you might have is software not being available. I'm using nasm for assembly.
main.c
extern void myFunc(char * somedata);
void main(){
myFunc("Hello World");
}
myFunc.asm
section .text
global myFunc
extern printf
myFunc:
push ebp
mov ebp, esp
push dword [ebp+8]
call printf
mov esp, ebp
pop ebp
ret
COMPILE
nasm -f elf myFunc.asm
gcc main.c myFunc.o -o main
Notes:
You need to install nasm (assembler) (ubuntu it is: sudo apt-get install nasm)
What basically happens in the c code calls the myFunc with a message. In myFunc.asm we get the address of the first character of the string (which is in [ebp+8] see here for information (http://www.nasm.us/xdoc/2.09.04/html/nasmdoc9.html see 9.1.2 which describes c calling conventions somewhat.) and we pass it to the printf function (by pushing it onto the stack). printf is in the c standard library which gcc will automatically link into our code by default unless we say not to.
We have to export myFunc in the assembly file and declare myFunc as an extrnal function in the main.c file. In myFunc.asm we are also importing the printf function from stdlib so that we can output the message as simply as possible.
Hope this helps somewhat.
精彩评论