从汇编调用 C
了解如何在汇编代码中调用 C 函数,并遵循标准调用约定。
从汇编调用 C 是 CoddyKit 上的免费 Assembly Language & x86 Low-Level Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Assembly Language & x86 Low-Level Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Assembly Language & x86 Low-Level Systems Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Bridge Assembly & C
Why would you want to combine C and Assembly code? It's a powerful technique in low-level and system programming!
- Assembly: Great for performance-critical tasks, direct hardware access, and understanding system internals.
- C: Offers high-level structure, portability, and access to vast libraries.
By calling C functions from Assembly, you can leverage C's complex logic and libraries while retaining Assembly's low-level control for specific tasks.
The Calling Contract
When one function calls another, they need to agree on a set of rules. This 'contract' is known as a calling convention.
It defines crucial aspects of how functions interact:
- How arguments are passed (e.g., on the stack, in registers).
- The order in which arguments are passed.
- Which function is responsible for cleaning up the stack after the call.
- How return values are transmitted back to the caller.
Without these conventions, your assembly code wouldn't know how to prepare data for a C function, or how to interpret its results.
Common `cdecl` Convention
The cdecl (C declaration) calling convention is very common, especially for 32-bit x86 systems (like Linux).
Let's look at its key characteristics:
- Argument Order: Arguments are pushed onto the stack from right to left.
- Stack Cleanup: The caller (your assembly code) is responsible for cleaning up the stack after the function returns.
- Return Values: Integer return values are typically placed in the EAX register.
Understanding cdecl is fundamental for successful interaction between your assembly and C code.
`cdecl` Argument Passing
With 32-bit cdecl, arguments are pushed onto the stack in reverse order. This means the last argument is pushed first, and the first argument is pushed last.
For a C function like my_func(arg1, arg2, arg3);, the assembly call would involve:
push dword arg3_valuepush dword arg2_valuepush dword arg1_valuecall my_func
This ensures that arg1 is at the 'top' of the arguments on the stack, just below the return address pushed by call.
Caller Cleans Up the Stack
One of the defining features of cdecl is that the caller (your assembly code) is responsible for removing the arguments from the stack after the C function returns.
This is typically done by adjusting the stack pointer (ESP) using the ADD ESP, N instruction, where N is the total size of the arguments pushed (e.g., 4 bytes per argument on 32-bit systems).
This cleanup mechanism allows C functions to accept a variable number of arguments (like printf) because the caller knows exactly how many arguments it pushed.
Handling Return Values
When a C function returns a value using cdecl, it places that value in a specific register for the caller to retrieve.
- For integer types (like
int,char,short), the return value is typically stored in the EAX register (on 32-bit x86). - For larger or floating-point types, other registers or memory locations might be used, but EAX is the most common for simple integer returns.
After the CALL instruction returns, you can simply access the EAX register to get the result from your C function.
Declaring External C Functions
Before your assembly code can call a C function, you need to tell the assembler that the function exists but is defined elsewhere. This is done using the extern directive.
Example: extern printf
This directive informs the assembler that printf is an external symbol. During the linking phase, the linker (e.g., gcc) will resolve this symbol to the actual C function's address, allowing your assembly program to execute it.
Example: Basic C Function Call
Let's call a simple C function that takes no arguments and returns nothing. We'll use 32-bit x86 assembly.
First, compile the C code (c_funcs.c):
#include <stdio.h>
#include <stdlib.h>
void greet_c() {
printf("Hello from C's greet_c()!\n");
}
// Placeholder for next example
int add_c(int a, int b) {
return a + b;
}
Now, try running this assembly code:
extern greet_c
extern exit
section .text
global _start
_start:
call greet_c ; Call the C function
; Exit the program
push dword 0 ; Exit status 0
call exit
Example: C with Args & Return
Now, let's call a C function that takes arguments and returns a value. Remember the cdecl rules for 32-bit x86:
- Arguments pushed right-to-left.
- Caller cleans the stack.
- Return value in EAX.
Add the add_c function to your c_funcs.c file (from the previous scene).
Then, run this assembly code:
extern add_c
extern exit
extern printf
section .data
format_str db "Result from C: %d", 0xA, 0
section .text
global _start
_start:
; Call add_c(10, 20)
; Arguments pushed right-to-left on 32-bit stack
push dword 20 ; Push b
push dword 10 ; Push a
call add_c ; Call the C function
; EAX now holds the return value (30)
; Clean up the stack (2 arguments * 4 bytes each = 8 bytes)
add esp, 8
; Now print the result using C's printf
; For 32-bit cdecl, printf args are pushed right-to-left
push eax ; Push result from add_c (in EAX)
push dword format_str ; Push format string address
call printf
add esp, 8 ; Clean up printf's arguments
; Exit the program
push dword 0 ; Exit status 0
call exit
Check Your Knowledge
Consider a C function int calculate(int x, int y, int z); that you want to call from 32-bit x86 assembly using the cdecl calling convention.
Which sequence of assembly instructions correctly prepares the stack and calls calculate with arguments x=5, y=10, z=15, and correctly cleans up the stack?
Recap: Calling C from Assembly
You've successfully learned how to integrate C functions into your assembly programs!
- Calling Conventions: These are crucial rules for function interaction.
cdecl(32-bit): Arguments are pushed onto the stack from right-to-left.- Caller Cleanup: The assembly code (caller) is responsible for removing arguments from the stack using
ADD ESP, N. - Return Values: Integer results from C functions are typically found in the EAX register.
externDirective: Use this to declare C functions to your assembler.
This skill allows you to combine the performance and low-level control of assembly with the rich features and libraries of C!
常见问题解答
「从汇编调用 C」课时是免费的吗?
是的 — 「从汇编调用 C」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Assembly Language & x86 Low-Level Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 Assembly Language & x86 Low-Level Systems Programming 课程共包含 4 节课。
「从汇编调用 C」这节课中我会学到什么?
了解如何在汇编代码中调用 C 函数,并遵循标准调用约定。 你通过在浏览器中直接运行的动手代码来练习 Assembly Language & x86 Low-Level Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Assembly Language & x86 Low-Level Systems Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Assembly Language & x86 Low-Level Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「从汇编调用 C」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Assembly Language & x86 Low-Level Systems Programming 课中编写并运行代码吗?
能。每节 Assembly Language & x86 Low-Level Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。