无法将参数从 C 传递给汇编代码 [英] Can't pass parameter from C to Assembly code
问题描述
据我了解,当在 C 中的函数调用中传递参数时,被调用者可以在 [ebp+8]
处找到第一个参数.
通过 eax
返回一个值对我有用,从堆栈中读取正确的参数值不起作用.
From what I understand, when a parameter is passed in a function call in C, the callee can find the first parameter at [ebp+8]
.
Returning a value through eax
works for me, reading the right parameter value from the stack doesn't.
现在我只是想写一个汇编函数,它可以从 C 调用并返回相同的值,它正在被传递.
Right now I'm just trying to write an assembly function, that can be called from C and returns the same value, that it is being passed.
当我运行以下程序时,它会将 number: 1
打印到控制台,无论将什么值传递给 myFunc
.我做错了什么?
When I run the following program, it prints number: 1
to the console, no matter what value is passed into myFunc
. What am I doing wrong?
assembly.s
section .text
global _myFunc
_myFunc:
mov eax, [ebp+8]
ret
main.c
#include <stdio.h>
extern unsigned int myFunc(unsigned int somedata);
int main() {
unsigned int i = myFunc(6);
printf("number: %i\n",i);
return 0;
}
我用的是 Mac,用 nasm 来汇编代码,用 gcc 来编译 C.
I'm using a Mac, nasm to assemble the code and gcc for C compilation.
Makefile
macho32:
nasm -f macho32 assembly.s
gcc -m32 -o macho32 assembly.o main.c
推荐答案
您通过从 [EBP+offset] 中读取来引用堆栈上的参数 - EBP 是否已设置为实际指向堆栈?如果不是,您可能必须先执行此操作,通常通过以下方式完成:
you refer to argument on stack, by reading from [EBP+offset] - has EBP been set up to actually point at stack? If no, you may have to do that first, conventionally done by:
push ebp
mov ebp,esp
然后才将 EBP 指向其堆叠的先前内容、堆叠的返回地址下方以及传递的参数下方.
Only then points EBP to its stacked previous contents, below stacked return address, and below passed arguments.
这篇关于无法将参数从 C 传递给汇编代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!