Pass an argument from C to assembly?

How can I pass an argument from a C main function to an assembly 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.

Answers


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.


Need Your Help

Appending circle shape to Path2D

java swing awt shape java-2d

So, to append a rectangle to a Path, you can do this

jQuery show.bs.collapse event for nested Bootstrap collapsible buttons fires on more buttons than expected

javascript jquery twitter-bootstrap nested

I'm using Bootstrap to make collapsible nested divs/buttons. I want to collapse all siblings of a div when it's expanded and to collapse all children of a div when it's collapsed (so that the expan...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.