将参数从C传递给汇编程序? [英] Pass an argument from C to assembly?
问题描述
如何将参数从C main函数传递给汇编函数?我知道我的自定义函数必须类似于:
How can I pass an argument from a C main function to an assembly function? I know that my custom function has to look something like:
void function(char *somedata) __attribute__((cdecl));
现在我将如何在汇编文件中使用somedata
.我的操作系统是Linux Ubuntu,处理器是x86.
Now how would I use somedata
in an assembly file. My operation system is Linux Ubuntu and my processor is x86.
推荐答案
对此我有点不满意,但希望本示例可以助您一臂之力.我已经对其进行了测试,并且可以正常工作,您唯一可能遇到的问题就是软件不可用.我正在使用nasm进行组装.
I'm a bit of a noob at this but hopefully this example will get you on your way. I've tested it and it works, the only issue you might have is software not being available. I'm using nasm for assembly.
extern void myFunc(char * somedata);
void main(){
myFunc("Hello World");
}
myFunc.asm
section .text
global myFunc
extern printf
myFunc:
push ebp
mov ebp, esp
push dword [ebp+8]
call printf
mov esp, ebp
pop ebp
ret
COMPILE
nasm -f elf myFunc.asm
gcc main.c myFunc.o -o main
注意:
您需要安装nasm(汇编程序)(ubuntu是:sudo apt-get install nasm)
Notes:
You need to install nasm (assembler) (ubuntu it is: sudo apt-get install nasm)
在C代码中发生的基本上是通过消息调用myFunc的消息.在myFunc.asm中,我们获取字符串的第一个字符的地址(在[ebp + 8]中,有关详细信息,请参见此处(http://www.nasm.us/xdoc/2.09.04/html/nasmdoc9.html参见9.1.2,它在某种程度上描述了c调用约定.),然后将其传递给printf函数(通过将其压入堆栈).printf在c标准库中,默认情况下,gcc会自动链接到我们的代码中,除非我们不说
What basically happens in the c code calls the myFunc with a message. In myFunc.asm we get the address of the first character of the string (which is in [ebp+8] see here for information (http://www.nasm.us/xdoc/2.09.04/html/nasmdoc9.html see 9.1.2 which describes c calling conventions somewhat.) and we pass it to the printf function (by pushing it onto the stack). printf is in the c standard library which gcc will automatically link into our code by default unless we say not to.
我们必须在程序集文件中导出myFunc,并在main.c文件中将myFunc声明为外部函数.在myFunc.asm中,我们还从stdlib导入了printf函数,以便我们可以尽可能简单地输出消息.
We have to export myFunc in the assembly file and declare myFunc as an extrnal function in the main.c file. In myFunc.asm we are also importing the printf function from stdlib so that we can output the message as simply as possible.
希望这会有所帮助.
这篇关于将参数从C传递给汇编程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!