备注: 这里给出的代码是在Win10系统中VS2022开发环境下编译测试通过的。
X86环境下C++调用汇编函数
c++代码:
#include <iostream>
// 函数使用 C 风格命名规范、调用规则
extern "C" int CalcSum_(int a, int b, int c);
int main(int argc, unsigned short* argv[])
{
int a = 17, b = 11, c = 14;
int sum = CalcSum_(a, b, c);
std::cout << " a: " << a << std::endl;
std::cout << " b: " << b << std::endl;
std::cout << " c: " << c << std::endl;
std::cout << " (x86)sum: " << sum << std::endl;
return 0;
}
x86汇编代码:
.model flat,c
.code
; extern "C" int CalcSum_(int a, int b, int c)
;
; Description: This function demonstrates passing arguments between
; a C++ function and an assembly language function.
;
; Returns: a + b + c
CalcSum_ proc
; x86处理器环境下, 参数由堆栈传入(依旧是从右向左入栈)
; Initialize a stack frame pointer
push ebp
mov ebp,esp
; Load the argument values
mov eax,[ebp+8] ; eax = 'a'
mov ecx,[ebp+12] ; ecx = 'b'
mov edx,[ebp+16] ; edx = 'c'
; Calculate the sum
add eax,ecx ; eax = 'a' + 'b'
add eax,edx ; eax = 'a' + 'b' + 'c'
; Restore the caller's stack frame pointer
pop ebp
ret
CalcSum_ endp
end
运行结果: