flat assembler
Message board for the users of flat assembler.

Index > OS Construction > Calling an assembly function with params from c

Thread Post new topic Reply to topic

Joined: 02 Apr 2012
Posts: 1
Location: Monroe, Michigan
How would create an assembly function containing some arguments to call from c and return a value?
Example code please would be helpful.

----------------------------------------------------------Not your average programmer.
Post 14 Oct 2012, 07:01
View user's profile Send private message Visit poster's website Reply with quote

Joined: 25 Aug 2004
Posts: 618
This is different depending on which compiler you use and the calling convention but the shape is the same. First you need to select the correct format for FASM to output:
format MS COFF ; 32bit VC (.obj)
format MS64 COFF ; 64bit VC (.obj)
format ELF ; 32bit GCC and others (.o)
format ELF64 ; 64bit GCC and others (.o)    
Next you will want to declare the functions you want to call from C; this is more tricky because of linker differences between cdecl, stdcall and fastcall as well as 32 or 64 bit. In FASM you can do this using public:
public my_function ; Simple extern
public my_function as '_my_function' ; Same as above but link name modified for calling convention    
Then you code the functions as normal but will have to account for the calling convention used:
        ; 64bit fastcall VC rax <- rcx, rdx
        ; unsigned long long my_function(unsigned long long x,void * p)

        mov rax,qword [rdx+8*rcx] ; return ((unsigned long long *)p)[i]

        ret ; no stack clean up

        ; 32bit cdecl (all) eax <- esp+4,...
        ; unsigned int my_function(unsigned int x,void * p)

        mov ecx,dword [esp+4]
        mov edx,dword [esp+8]

        mov eax,dword [edx+4*ecx] ; return ((unsigned int *)p)[i]

        ret ; no stack clean up      
To call from C, you declare the functions from above as externs and add you .o or .obj to the link stage in your C build - if you get linker errors this will likely be due to the name in the FASM object not matching the one expected by C so this may need to be adjusted.

Hopefully this is enough to point you in the right direction but if you have a specific case (compiler/convention/function) it is easier to work to.
Post 14 Oct 2012, 11:22
View user's profile Send private message Reply with quote
Display posts from previous:
Post new topic Reply to topic

Jump to:  

< Last Thread | Next Thread >
Forum Rules:
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum

Copyright © 1999-2020, Tomasz Grysztar. Also on GitHub, YouTube, Twitter.

Website powered by rwasa.