Asm和VC混合编程

mac2024-08-11  48

Asm和VC混合编程_数据传送(1)

(一) Win32保护模式下masm编程

环境 masm + masm plus

注意一下,不同的汇编编译器,编写的汇编码格式上有所不同,这里使用masm。(gcc生成汇编码:gcc -S test.c)

masm plus新建Win32 Console项目

;MASMPlus 代码模板 - 控制台程序 ;swap_bytes.asm .386 .model flat, stdcall option casemap :none include windows.inc include user32.inc include kernel32.inc include masm32.inc include gdi32.inc includelib gdi32.lib includelib user32.lib includelib kernel32.lib includelib masm32.lib include macro.asm .data lpMsg db "Hello World!",0 RST DB 'BL = , BH = ',0DH,0AH,0 TEMP DB ? .data? buffer db MAX_PATH dup(?) .CODE START: invoke locate,30,10 ;设定输出文本的坐标 ;invoke StdOut,offset lpMsg MOV BL, 'A' MOV BH, 'B' MOV TEMP, BL MOV BL, BH MOV BH, TEMP mov RST+5, BL mov RST+13, BH invoke StdOut,offset RST invoke StdIn,addr buffer,sizeof buffer invoke ExitProcess,0 end START

上面实现两个字符交换,与8086编程不同,386的flat模式(段最大为4G))下无需设定CS DS ES SS,masm自动初始化。 .data : 数据段,一般放在_DATA Section内 .data? : 可读可写的未定义变量,一般当为缓冲区,.data?不会增大exe文件大小,一般放在_BSS Section内 .const : 可读不可写,一般放常量 .CODE : 代码段,一般在_TEXT Section invoke StdOut : 调用系统api的输出函数 invoke StdIn : 调用系统api的输入函数,防止程序退出

关于8086过渡到80386汇编编程

可以参照罗云彬的《Windows环境下32位汇编语言程序设计》,但更详细的应参照Microsoft masm 的说明书 《Programmer's Guide》。

(二) VC调用Asm - 数据传送

环境VC++ 6.0

#include<stdio.h> #include<stdlib.h> int main() { char temp; //switch to assembly _asm { nop nop nop push eax xor eax,eax mov al,'a' mov temp,al pop eax } //print result printf ("al = %c\n",temp); system("pause"); return 0; }

说明 在_asm{}中插入汇编码 nop空指令,为了在动态调试中快速找到_asm{}中的代码,也可以加入调试宏 push eax和pop eax : 由于使用到eax寄存器,赋值完temp后,恢复eax的值(eax可能放一些重要数据,如果不这样做可能导致程序异常) mov al,'a' : 要特别注意数据的长度 system("pause"); : 防止程序退出

关于源码调试

VC++ 6.0设置断点调试可以直接查看汇编码 VC++ 2010设置断点在调试\窗口\反汇编中查看汇编码 用x64debug,ollydbg等动态调试时,把源码项目改为Release _asm{}反汇编:

00401004 | 90 | nop | 00401005 | 50 | push eax | 00401006 | 33C0 | xor eax,eax | 00401008 | B0 61 | mov al,61 | 61:'a' 0040100A | 8845 FF | mov byte ptr ss:[ebp-1],al | 0040100D | 58 | pop eax |

关于编译错误

VC编译错误 : https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-errors-c2000-c3999?view=vs-2019 ml编译错误 : https://docs.microsoft.com/en-us/cpp/assembler/masm/ml-error-messages?view=vs-2019

(三) 参考
Microsoft® MASM : Programmer's GuideX86 Assembly Language and C Fundamentals [Cavanagh 2013-01-22]
最新回复(0)