WriteConsole returns 在 MASM 中为假

WriteConsole returns false in MASM

我正在尝试创建一个数组,访问它的值并将它们打印出来

调用 WriteConsole 子例程后,它返回 false,但是,所有值都已提供。在这里我们可以看到 - https://imgur.com/a/vUfwOo6 调用 WriteConsole 后 Eax 寄存器为 0。在这里您可以看到被压入堆栈的寄存器值。 https://imgur.com/a/gv6s4uG 考虑到,WriteConsole 是 WINAPI 子例程,这意味着它是 stdcall。所以,我从右到左传递值。

lpReserved -> 0
lpNumberOfCharsWritten -> offset to 00403028 (CharsWritten variable)
nNumberOfCharsToWrite -> Just 2, because in array only ints are present of length 2
*lpBuffer -> ebx register, which contains array lvalue
hConsoleOutput -> Output from GetStdHandle (In this case -> edx register -> A0)

我的 MASM 代码:

.386
.model flat,stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib
include \masm32\include\user32.inc
include C:\masm32\include\masm32.inc
includelib C:\masm32\lib\masm32.lib
includelib \masm32\lib\user32.lib
includelib \masm32\lib\msvcrt.lib ; Some default includes :P

.data

dArray              dd  10 dup (?)      ; Main array
CharsWritten        dd ?
LoopCounter         dd 0
StdHandle           dd ?
.code


PrintArrayToScreen proc

mov eax, STD_OUTPUT_HANDLE
push eax
call GetStdHandle

mov StdHandle,eax
mov eax,[LoopCounter]
innerPrintLoop:
mov ecx,offset dArray
mov eax, [LoopCounter]
mov ebx,[ecx + eax * 4]
mov esi,offset CharsWritten

push 0
push esi
push 2
push ebx
mov edx,StdHandle
push edx

call WriteConsole

mov eax,[LoopCounter]
inc eax
mov LoopCounter,eax ; Storing the Loop Counter in the variable
cmp eax,11  ; +1 because of loop counter increment
jnz innerPrintLoop
ret
PrintArrayToScreen endp

arrayLoop proc          ; Subroutine for the array filling
mov eax,offset dArray
mov bx,10
mov ecx,0
innerLoop:
mov [eax + ecx * 4],bx  ; ecx * 4 => counter * 4 bytes
inc bx
add ecx,1
cmp ecx,10
jne innerLoop
mov eax,offset dArray
ret
arrayLoop endp

start:
call arrayLoop
call PrintArrayToScreen
mov eax,0
push eax
call ExitProcess
end start

来自 the documentation WriteConsole:

lpBuffer [in]
A pointer to a buffer that contains characters to be written to the console screen buffer.

所以您应该传递要写入的数据的地址,但实际上您传递的是数据本身。

您可以通过将行 mov ebx,[ecx + eax * 4] 更改为 lea ebx,[ecx + eax * 4] 来“解决”这个问题。但请注意 WriteConsole 不会为您做任何 integer-to-string 转换,因此您仍然可能无法获得预期的结果。如果您想要那种功能,请使用 printf.