【问题标题】:Printing a C++ array through assembly通过汇编打印 C++ 数组
【发布时间】:2017-12-12 19:09:06
【问题描述】:

目前,我遇到了很多问题。当我调试我的代码时,我的 C++ 正常运行,直到我到达汇编函数调用,它在我的汇编代码中跳转到 L2 而不是 L1。我不确定它为什么这样做。最重要的是,我正在尝试将数组打印到屏幕上,但到目前为止,我只是得到了一个巨大的数字。我尝试包含 Irvine 的库并使用“WriteDec”尝试打印出元素,但该库甚至无法被识别。

下面是我当前的汇编代码,用于从 C++ 代码中获取 3 个数组,并将它们加在一起。

.model flat, C
.model flat, STDCALL

.code
ASMsumarray PROC,
ptr1:PTR DWORD,     ; points to array
ptr2:PTR DWORD,     ; points to array
ptr3:PTR DWORD      ; points to array
pushad              

    mov esi,ptr2  
    mov edi,ptr3  
    mov ecx,10    

    L1:
        mov ebx,[edi]  ;mov first elem of ptr3 to ebx
        add ebx,[esi]  ;add elem from ptr2 to ebx
        mov [esi],ebx  ;mov ebx to spot in ptr2. ptr2 elem now contains sum of ptr2 and 3
        add edi,4
        add esi,4
    loop L1
        mov edi,ptr1  ;mov ptr1 to esi
        mov ecx,10    ;mov ptr2 to edi
        sub edi,40
        sub esi,40
    L2:
        mov ebx,[edi]  ;mov first elem of ptr2 to ebx
        add ebx,[esi]  ;add elem from ptr1 to ebx
        mov [esi],ebx  ;mov ebx to spot in ptr1. ptr1 elem now contains sum of ptr1 and 2
        add edi,4
        add esi,4
    loop L2

    popad               ;//pop registers off the stack
        ret
ASMsumarray ENDP

这是 C++ 代码。

#include <iostream>
#include <ctime>

using namespace std;

extern "C" int ASMsumarray(int array1[], int array2[], int array3[]);

int main() {
    srand(time(NULL));      //seed rand num     

    int array1[10] = { 1,1,1,1,1,1,1,1,1,1 };
    int array2[10] = { 1,1,1,1,1,1,1,1,1,1 };
    int array3[10] = { 1,1,1,1,1,1,1,1,1,1 };
/*
    for (int i = 0; i < 10; i++) {
    array1[i] = rand() % 10;
    array2[i] = rand() % 10;
    array3[i] = rand() % 10;
    cout << endl;
    }
    cout << endl;
    */

    //for (int i = 0; i < 10; i++) {
    //cout << array1[i] << endl;
    //}

    cout << "The number is " << ASMsumarray(array1, array2, array3) << endl;
    return 0;
}

【问题讨论】:

  • sub edi,40 是错误的。你刚刚从ptr1 加载了edi,你不应该从中减去。顺便说一句,重新加载 esi 而不是减去也更易读。
  • 标题有点误导,因为它们通常被称为 c 数组,而 c++ 有一个 std::array
  • 请问您使用汇编代码这样做的原因是什么?
  • @user0042 实验室上课。教授只告诉我我的增量已关闭,这是一个愚蠢的错误,但我被难住了。
  • 你有mov edi,ptr1,然后是sub edi,40。这没有任何意义。

标签: c++ arrays assembly x86


【解决方案1】:

最重要的是,我正在尝试将数组打印到屏幕上,但截至目前,我得到的只是一个巨大的数字。

您的函数应该返回一个int,但您使用popad 来恢复所有 寄存器,包括调用者的eax 值。所以你的返回值是调用者在eax中留下的任何垃圾。

此外,您永远不会在 eax 中输入值:您使用的调用约定需要 eax 中的返回值,就像几乎所有 x86 调用约定一样。

只需使用push / pop 保存/恢复您实际需要使用的调用保留寄存器。 (并尽可能少地使用,例如使用eax、ecx 和edx 作为指针和临时对象。)


顺便说一句,你的 C++ 调用者没有打印数组,它只是打印 sum(函数返回值)。您的函数的返回值是一个标量。不清楚为什么要修改数组内容。


当我调试我的代码时,我的 C++ 正常运行,直到我到达汇编函数调用,它在我的汇编代码中跳转到 L2 而不是 L1。

这没有任何意义。确保在实际函数入口点(不是 L1 或 L2)设置断点。或者通过单个指令单步执行您的函数,而不是通过 C 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多