简体   繁体   English

C 中使用的 NASM 过程。是否可以修改在 C 中调用的函数中使用的参数,该函数是 NASM 中的过程?

[英]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):基本上我想更改下面 C 代码中使用的变量a (不做a = add(a, 6);因为我打算使用多个需要在不同函数中更改的参数,这些参数将用于模拟与 NASM 链接以执行每条指令的 C 语言 CPU):

//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 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.我正在考虑使用宏,但到目前为止我发现我认为使用 nasm 是不可能的。

It does not matter how the called function is implemented, C or assembler or any other language.被调用的函数是如何实现的,C 或汇编程序或任何其他语言都无关紧要。 As you are giving both argument to the function by value , it cannot change the original variables, they are copies.由于您通过 value为函数提供了两个参数,因此它无法更改原始变量,它们是副本。

You need to pass references , in C these are the addresses of the variables to change.您需要传递引用,在 C 中这些是要更改的变量的地址。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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