X86和X64运行环境下C++调用汇编函数源码和解释

备注: 这里给出的代码是在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

运行结果:

X64环境下C++调用汇编函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值