Using an array in embedded x86 assembly?

2019-05-23 04:30发布

I have a method (C++) that returns a character and takes an array of characters as its parameters.

I'm messing with assembly for the first time and just trying to return the first character of the array in the dl register. Here's what I have so far:

char returnFirstChar(char arrayOfLetters[])
{
 char max;

 __asm
 {
  push eax
      push ebx
       push ecx
     push edx
  mov dl, 0

  mov eax, arrayOfLetters[0]
  xor edx, edx
  mov dl, al

  mov max, dl       
  pop edx
  pop ecx
  pop ebx
  pop eax

 }

 return max;
}

For some reason this method returns a ♀

Any idea whats going on? Thanks

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-23 05:01

The line of assembly:

mov eax, arrayOfLetters[0]

is moving a pointer to the array of characters into eax (note, that's not what arrayOfLetters[0] would do in C, but assembly isn't C).

You'll need to add the following right after it to make your little bit of assembly work:

mov al, [eax]
查看更多
ゆ 、 Hurt°
3楼-- · 2019-05-23 05:08

Well here is how I'd write that function:

char returnFirstChar( const char arrayOfLetters[] )
{
    char max;
    __asm
    {
         mov eax, arrayOfLetters ; Move the pointer value of arrayOfLetters into eax.
         mov dl, byte ptr [eax]  ; De-reference the pointer and move the byte into eax.
         mov max, dl             ; Move the value in dl into max.
    }
    return max;
}

That seems to work perfectly.

Notes:

1) As I said in my comment you don't need to push the registers on the stack, let MSVC handle that.
2) Don't bother clearing edx by X'oring it against it self or don't set dl to 0. Both will achieve the same thing. All in you don't even need to do that as you can just overwrite the value stored in dl with your value.

查看更多
登录 后发表回答