开发者

C/C++ Inline assembly [with C loops]

#include <stdio.h>

#define OPT //define for assembly

int main()
{
 char chr;
 for(chr = 'A' ; chr <= 'Z' ; chr++)
 {
  #ifdef OPT
  __asm
  {
   lea eax,chr
   push eax
   mov eax, putchar
   call eax
   pop ebx
  }
  #endif

  #ifndef OPT
  putchar(chr);
  #endif 
 }
 return 0;
}

Upon usage of the assembly code, all that happens is a random trash-character is printed. Note this is in intel syntax.

Also: I'm learning inline assembly, how would you grab the return value开发者_运维问答 of a called function (through mov eax,func then call eax or equiv?)


It doesn't work because lea instruction is intended to get the address of a variable. (+1 to zebarbox for this note.) We need the value of chr, not its address, so we use this instead:

movsx eax,chr

This pseudoinstruction will compile to something like this:

movsx eax,[ebp-4]

You can also write putchar(chr), put there a breakpoint, run the application and look into disassembly window to see how it is compiled.

Note that I use movsx because chr is char and I need here a dword. If chr was int, I would simply use mov instruction.

Also, you are not allowed to use pop ebx, because ebx must not be changed here. Use pop eax or add esp,4 instead.


Here is your correct code:

int c = chr;
__asm
{
   mov  eax, c
   push eax
   mov  eax, putchar
   call eax
   pop  ebx
}

You cannot move chr on eax, due to size-conflict. So I used 'c' of int type!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜