汇编语言

创建日期:2024-06-21
更新日期:2024-12-01

Visual Studio编写汇编语言

#include<stdio.h>

void main()
{
 int a = 1;
 int b = 2;
 int sum = 0;

 /* 使用汇编语言将两个数字相加 */
 __asm {
  mov eax, a; // 将内存中的a变量移动到eax寄存器中
  add eax, b; // 将内存中的b变量加到eax寄存器中
  mov sum, eax; // 将eax寄存器中的内容移动到内存中的sum变量中
 }

 printf("The result is %d.\n", sum); // 输出相加结果
}

调用函数

#include<stdio.h>

/* 两个数相加 */
int __cdecl addInt(int a, int b)
{
 return a + b;
}

void main()
{
 int a = 1;
 int b = 1;
 int sum = 0;

 /* 使用汇编语言调用函数将两个整数相加 */
 __asm {
  // 将参数从右至左压入堆栈
  mov eax, b; // 将变量b放到eax寄存器中
  push eax; // 将eax压入堆栈

  mov eax, a; // 将变量a放到eax寄存器中
  push eax; // 将eax中的值压入堆栈

  call addInt; // 调用addInt方法
  mov sum, eax; // 将结果存到sum变量中

  pop eax; // 平衡堆栈(addInt为__cdecl时调用者需要平衡堆栈,__stdcall时调用者不需要平衡堆栈)
  pop eax;
 }

 printf("The result is: %d.\n", sum);
}

调用Windows API

#include<Windows.h>

void main()
{
 /* MessageBox函数参数 */
 HANDLE hWnd = NULL; // 父窗口句柄
 LPCTSTR lpText = TEXT("世界,你好!"); // 内容
 LPCTSTR lpCaption = TEXT("标题"); // 标题
 UINT uType = MB_OK; // 消息框按钮

 __asm {
  // 将MessageBox的参数从右至左压入堆栈
  mov eax, uType;
  push eax;
  mov eax, lpCaption;
  push eax;
  mov eax, lpText;
  push eax;
  mov eax, hWnd;
  push eax;

  // 调用Windows API函数
  call MessageBox;
 }
}