c++ - 如何在我的汇编代码中调用 C++ 函数

标签 c++ assembly

我需要从程序集中调用 PrintResult 来显示结果。我知道我必须在某处使用 extrn _PrintResult,并且我应该使用 call _PrintResult 来调用该函数,但我不太确定如何使用它。有什么建议

public _Square

.386

.model flat

.code

_Square proc

mov eax, [esp+4]

imul eax

ret

_Square endp

............这是我的 C++ 代码......

#include <iostream>

using namespace std;

enum ResultCode {ShowSquare};
enum SuccessCode {Failure, Success};

extern "C" long Square (long);

void main ()
 {
 long Num1; 
         long Num2;

 do
  {
  cout << "Enter Number to Square" << endl;
  cin >> Num1;
  Result = Square (Num1);
  cout << "Square is: " << Result << endl;
  } while (Result > 0);
 }

void PrintResult (ResultCode PrintCode, long Value) //PrintCode, long Value)
 {
 switch (PrintCode)
  {
  case ShowSquare:
    cout << "Display of square is: " << Value << endl;
    break;

  default:
    cout << "Error in assembly routines" << endl;
  }
}

最佳答案

我通常不喜欢发布完整的代码,但请尝试一下:

32 位汇编

.386
.model flat
.code

_Square proc
mov eax, [esp+4]
imul eax

push eax ; Save the calculated result

; Call PrintResult here
push eax ; value
push 0 ; ShowSquare
call _PrintResult
add esp, 8 ; Clear the stack

pop eax ; Return the calculated result

ret
_Square endp

C++

#include <iostream>

using namespace std;

enum ResultCode {ShowSquare};
enum SuccessCode {Failure, Success};

extern "C" long Square(long);

int main(int argc, char* argv[])
{
    long Num1, Num2;

    do
    {
        cout << "Enter number to square" << endl;
        cin >> Num1;
        Num2 = Square(Num1);
        cout << "Square returned: " << Num2 << endl;
    }
    while (Num2);

    return 0; 
}

extern "C"
void PrintResult(ResultCode result, long value)
{
    switch (result)
    {
        case ShowSquare:
            cout << "Square is: " << value << endl;
            break;

        default:
            cout << "Error calculating square" << endl;
            break;
    }
}


因为你写的是C程序,所以默认的调用机制是cdecl这意味着所有参数都在堆栈上传递,返回值在eax中传回,调用者负责随后清理堆栈。

因此,为了调用 PrintResult,您必须在调用该过程之前将所有参数压入堆栈。程序返回后,我们必须清理堆栈(add esp, 8)。

因为cdecl调用约定允许eax在调用过程中被修改,eax在PrintResult返回时可能不会被保留,所以我们在调用PrintResult之前保存计算结果,然后在调用之后恢复它返回。

我还没有尝试过上面的代码,但我希望它能帮助您走上正确的道路。


注意:由于您使用的是 C++ 编译器,因此 PrintResult 之前的 extern "C" 是必需的。

关于c++ - 如何在我的汇编代码中调用 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3911578/

相关文章:

c++ - 如何检查应用程序本身的校验和?

c++ - 具有某些成员的类的术语

java - 跨语言(Java、C++、Python)系统使用哪个日志库

assembly - 为什么 x86 汇编中一个字是 2 个字节而不是 4 个字节?

c++ - 如何将处理器速度的汇编代码移植到 Visual Studio 2008

c++ - 使用此指针指向类中的位域

c++ - 字符指针在简单的 Boyer-Moore 实现中搞砸了

c++ - Nasm,C++,传递类对象

opencv - 优化SIMD直方图计算

assembly - 从头开始编写 ELF64 时执行错误