将参数从 C++ 传递到 cout 中的程序集

Passing arguments from c++ to assembly in cout

我正在编写 C++ 和 nasm 汇编 atm 的简单组合,不明白为什么 "cout" 内部和外部的结果不同。也许这是某种例外,但我想知道 difference.Thanks 以寻求任何帮助。

C++ 部分

#include <iostream>
#include <cstring>
using namespace std;
extern "C" unsigned int quot (unsigned int, unsigned int);
extern "C" unsigned int remainder (unsigned int, unsigned int);

int main()
{
    unsigned int i=0, j=0, k=0;
    cout << "Numbers 'x y'" << endl;
    cin >> i >> j;
    k = quot(i,j);
    cout<< "Result: " <<k;
    k = remainder(i,j);
    cout <<" r. "<< k <<endl;

    cout << "Result: "<<quot(i,j)<<" r. "<<remainder(i,j)<<endl;

    return 0;
}

NASM quot 和提醒功能几乎相同。唯一的区别在代码中注释

section .data

section .text
    global quot

quot:
    ; intro 
    push ebp         
    mov ebp,esp      

    xor edx, edx     
    mov eax, [ebp+8] 
    mov ebx,[ebp+12] 

    div ebx

    ; DIFFERENCE: in remainder we have additionaly
    ; mov eax, edx

    mov esp,ebp 
    pop ebp  
    ret      

结果 对于 12 5 输入,我们期望结果:2 r。 2 但我们得到。

Result: 2 r. 2
Result: 2 r. 5

您必须在您的 asm 函数中保留 ebx 的值(参见 http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl)。违反调用约定可能会导致各种错误,从细微到崩溃。

使用 ecx 代替 ebx,或尝试 div dword ptr [ebp+12]