gpt4 book ai didi

c++ - 如何在 C++ 中使用内联函数进行内联汇编?

转载 作者:行者123 更新时间:2023-11-30 04:22:45 24 4
gpt4 key购买 nike

我尝试将 C++ 工具移植到 VS2005 中的 x64。问题是,代码包含内联汇编,64 位编译器不支持它。我的问题是,是否有更多的努力用清晰的 C++ 或使用内在函数来编码。但在这种情况下,并非所有汇编程序函数都可用于 x64,对吗?比方说,我有一个简单的程序

#include <stdio.h>

void main()
{
int a = 5;
int b = 3;
int res = 0;

_asm
{
mov eax,a
add eax,b
mov res,eax
}

printf("%d + %d = %d\n", a, b, res);
}

我必须如何使用内部函数更改此代码才能运行它?我是汇编程序的新手,不了解它的大部分功能。

更新:

我按照 Hans 的建议更改了使用 ml64.exe 编译程序集。

; add.asm

; ASM function called from C++

.code
;---------------------------------------------
AddInt PROC,
a:DWORD, ; receives an integer
b:DWORD ; receives an integer
; Returns: sum of a and b, in EAX.
;----------------------------------------------
mov eax,a
add eax,b
ret
AddInt ENDP
END

main.cpp

#include <stdio.h>

extern "C" int AddInt(int a, int b);

void main()
{
int a = 5;
int b = 3;
int res = AddInt(a,b);

printf("%d + %d = %d\n", a, b, res);
}

但结果不正确 5 + 3 = -1717986920。我想,指针出了点问题。我哪里做错了?

最佳答案

VC 中的 64 位目标不支持内联汇编。

关于您的非内联代码中的错误,乍一看代码似乎没有问题。我会查看从 C++ 生成的汇编代码 - 看它是否与 addInt 过程匹配。

编辑:注意两点:

  1. extern addInt :proc 添加到您的 asm 代码中。
  2. 我不知道过程接受参数的汇编语法。参数通常根据您的调用约定通过堆栈指针(sp 寄存器)提取,请在此处查看更多信息:http://courses.engr.illinois.edu/ece390/books/labmanual/c-prog-mixing.html

关于c++ - 如何在 C++ 中使用内联函数进行内联汇编?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13623085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com