用VC写Assembly代码(4)

本文探讨了在VC++中使用__asm关键字配合printf函数的问题。通过示例代码展示了如何正确传递参数,并分析了错误做法导致的输出差异。最后给出了正确实现printf调用的__asm代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在汇编中使用printf没什么意义,这里只说明一写问题,printf 再 __asm中的使用有点复杂.先看看下面代码:

void main()
{
 int t = 10;
 char *szformat = "t = %d/n";
 printf(szformat, t);
}

===
输出

t = 10
Press any key to continue

调试得到的汇编代码:

19:   void main()
20:   {
0040B770   push        ebp
0040B771   mov         ebp,esp
0040B773   sub         esp,48h
0040B776   push        ebx
0040B777   push        esi
0040B778   push        edi
0040B779   lea         edi,[ebp-48h]
0040B77C   mov         ecx,12h
0040B781   mov         eax,0CCCCCCCCh
0040B786   rep stos    dword ptr [edi]
21:       int t = 10;
0040B788   mov         dword ptr [ebp-4],0Ah
22:       char *szformat = "t = %d/n";
0040B78F   mov         dword ptr [ebp-8],offset string "%d/n" (0041ff6c)
23:       printf(szformat, t);
0040B796   mov         eax,dword ptr [ebp-4]
0040B799   push        eax
0040B79A   mov         ecx,dword ptr [ebp-8]
0040B79D   push        ecx
0040B79E   call        printf (0040b6f0)
0040B7A3   add         esp,8
24:   }

如果我们用感觉上的方法写个__asm 代码,会写成这样(我一开始是写成这样的):

#include <stdio.h>

void asm()
{
 int t = 10;
 char *szformat = "t = %d/n";
 __asm
 {
  push t
  lea eax, szformat
  push eax
  call printf
  add esp, 8
 }
}

void main()
{
 asm();
}

===
输出

lAPress any key to continue

哦,不!怎么和我们要的完全不一样呢?
怎么办,先看看他的汇编代码:

3:    void asm()
4:    {
0040B770   push        ebp
0040B771   mov         ebp,esp
0040B773   sub         esp,48h
0040B776   push        ebx
0040B777   push        esi
0040B778   push        edi
0040B779   lea         edi,[ebp-48h]
0040B77C   mov         ecx,12h
0040B781   mov         eax,0CCCCCCCCh
0040B786   rep stos    dword ptr [edi]
5:        int t = 10;
0040B788   mov         dword ptr [ebp-4],0Ah
6:        char *szformat = "t = %d/n";
0040B78F   mov         dword ptr [ebp-8],offset string "%d/n" (0041ff6c)
7:        __asm
8:        {
9:            push t
0040B796   push        dword ptr [ebp-4]
10:           lea eax, szformat
0040B799   lea         eax,[ebp-8]
11:           push eax
0040B79F   push        eax
12:           call printf
0040B7A0   call        printf (0040b6f0)
13:           add esp, 8
0040B7A5   add         esp,8
14:       }
15:   }


代码区别很明显,很快我得出一下代码:

#include <stdio.h>

void asm()
{
 int t = 10;
 char *szformat = "t = %d/n";
 __asm
 {
  mov eax, t
  push eax
  mov ecx, dword ptr [ebp-8]
  push ecx
  call printf
  add esp, 8
 }
}

void main()
{
 asm();
}

===
输出

t = 10
Press any key to continue

哦!不说了,有什么不清楚,上BAIDU找找吧(虽然GOOGLE更好).

有人愿意说明一下原因吗?谢谢.

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值