简体   繁体   中英

NASM Procedure used in C. Is it possible to modify the arguments used in a function called in C that is a procedure in NASM?

Basically I want to change the variable a that is used in the C code below (without doing a = add(a, 6); because I intend to use multiple parameters that need to be changed in different functions that will be used for simulating a CPU in C that is linked with NASM for performing each instruction):

//main.c
#include <stdio.h>

extern int add(int a, int b);

int main(void){
    int a = 4;
    printf("%d\n", add(a, 6)); //Prints 10
    printf("%d\n", a);         //Prints 4, I want it to maintain the value
    return 0;
}

Here's the assembly code:

;add.asm
global add

add:
    mov eax, [esp + 4] ;argument 1
    add eax, [esp + 8] ;argument 2
    ret

And I compile it with: nasm -f elf add.asm ; gcc -m32 main.c add.o ; ./a.out nasm -f elf add.asm ; gcc -m32 main.c add.o ; ./a.out

The code above is a representation of what I want to achieve. I was thinking of using macros but for what I've found so far I think it's impossible using nasm.

It does not matter how the called function is implemented, C or assembler or any other language. As you are giving both argument to the function by value , it cannot change the original variables, they are copies.

You need to pass references , in C these are the addresses of the variables to change.

Your assembler function simply changes the passed parameter. This is allowed and OK, but it does not affect the variables in the caller. You might like to look at parameters as local function variables.

Change the function to pass a pointer, then modify the value of the pointee:

extern int add(int *a, int b);

...

printf("%d\n", add(&a, 6)); //Prints 10

In assembly code this means that one extra level of indirection is used. So the code eg looks like this:

;add.asm
global add

add:
    mov ecx, [esp + 4] ; pointer to argument 1
    mov eax, [esp + 8] ; argument 2
    add eax, [ecx]     ; *a + b
    mov [ecx], eax     ; *a = *a + b
    ret

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM