How to call function in Assembly inline from code in C and vice versa

Asked

Viewed 149 times

0

I am using the MASM syntax to make the codes below.
I tried with this function, for example:

__asm(
    "soma:\n"
    "push ebp\n"
    "mov ebp, esp\n"
    "mov eax, DWORD PTR[ebp+8]\n"
    "mov edx, DWORD PTR[ebp+12]\n"
    "add eax, edx\n"
    "pop ebp\n"
    "ret"
);

and made that call

int main(){
    int result;
    result = soma(10,7);
    printf("%d",result);
}

In this case, the Assembly function was not set to C and then the call failed.
In the same way I tried to do it backwards:

int soma(int x,int y){
    return (x+y);
}

With the following call

int main(){
int result; /*Colocado em  ebp-12 neste caso particular */
    __asm(
        "push 7\n"
        "push 10\n"
        "call soma\n"
        "add esp, 8\n"
        "mov DWORD PTR[ebp-12],eax" /* coloca 17 no result */
    );
    printf("%d",result);

}

I analyzed the generated Assembly on the site godbolt and both codes generate the same Assembly but neither of the two works. However, if I use Assembly for the function and Assembly for the call it will work just as if I use C for the function and C for the call. I want to bring the two together somehow.

Both C code and Assembly code will work normally, but either of the two mixtures failed
The problem in both mixtures was Undefined Reference to`sum'

The code in Assembly will compile using the command below

gcc -m32 -masm=intel sum.c

1 answer

0

Half of the problem was solved after suggestion.
How to run Assembly inline in a code with variables in C?
In this way it is possible to call a function in C from Assembly inline.

#include <stdio.h>

int soma(int x,int y){
    return (x+y);
}   




int main(){
int result; 
    __asm(
        "push 7\n"
        "push 10\n"
        "call ebx\n"
        "add esp, 8"
:"=a" (result)
:"b" (soma)

    );
    printf("%d",result);

}

A possible solution for the second part (without being 100% Assembly inline) is to remove the instructions push ebp ; mov ebp,esp;
pop ebp and ret and make the whole body of the function in Assembly, in an equivalent way.

#include <stdio.h>

int soma(int x,int y){
    __asm(
    "mov eax, DWORD PTR[ebp+8]\n"
    "mov edx, DWORD PTR[ebp+12]\n"
    "add eax, edx\n" /*  eax contém o valor a ser retornado da função */
);
}   




int main(){
int result; 
result = soma(7,10);
    printf("%d",result);

}

There is still the problem of doing the function fully in Assembly inline and it is still possible to make a function call in C

Browser other questions tagged

You are not signed in. Login or sign up in order to post.