Pass an argument from C to assembly?

北慕城南 提交于 2019-11-29 08:44:43

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!