案例代码
01.addThree 外联汇编
test.asm
;测试函数 三个数相加
.model flat, c
.code
addThree_ proc
;初始化栈帧指针
push ebp
mov ebp,esp
;加载参数值
mov eax,[ebp+8]
mov ecx,[ebp+12]
mov edx,[ebp+16]
;求和
add eax,ecx
add eax,edx
;恢复父函数的栈帧指针
pop ebp
ret
addThree_ endp
end
main.cpp
//main.cpp
#include <stdio.h>
#include <stdlib.h>
extern "C" int addThree_(int a, int b, int c);
int main()
{
int a = 17;
int b = 20;
int c = 19;
int sum = addThree_(a, b, c);
printf("c = %d\n", sum);
system("pause");
return 0;
}
02.addThree 内嵌汇编
#include <stdio.h>
#include<stdlib.h>
int main()
{
int a = 1, b = 2, c = 3;
__asm//这里是双下划綫
{
push eax
mov eax, a
add eax, b
add eax, c
mov a, eax
pop eax
}
printf("%d", a);
system("pause");
return 0;
}
03.findArray
findarr.h
// findarr.h
extern "C"
{
bool AsmFindArray(long n, long array[], long count);
// Assembly language version
}
AsmFindArray.asm
TITLE FindArray Procedure (AsmFindArray.asm)
; This version uses hand-optimized assembly language
; code with the SCASD instruction.
.586
.model flat,C
AsmFindArray PROTO,srchVal:DWORD, arrayPtr:PTR DWORD, count:DWORD
.code
;-----------------------------------------------
AsmFindArray PROC USES edi,srchVal:DWORD, arrayPtr:PTR DWORD, count:DWORD
;
; Performs a linear search for a 32-bit integer
; in an array of integers. Returns a boolean
; value in AL indicating if the integer was found.
;-----------------------------------------------
true = 1
false = 0
mov eax,srchVal ; search value
mov ecx,count ; number of items
mov edi,arrayPtr ; pointer to array
repne scasd ; do the search
jz returnTrue ; ZF = 1 if found
returnFalse:
mov al, false
jmp short exit
returnTrue:
mov al, true
exit:
ret
AsmFindArray ENDP
END
main.cpp
// main.cpp - Testing the FindArray subroutine.
#include <stdlib.h>
#include <iostream>
#include "findarr.h"
using namespace std;
int main()
{
const unsigned ARRAY_SIZE = 100 ;
long array[ARRAY_SIZE] ;
// Fill the array with pseudorandom integers.
for (unsigned i = 0; i < ARRAY_SIZE; i++)
{
array[i] = rand();
//cout << array[i] << " ";
}
cout << "\n\n";
long searchVal;
cout << "Enter an integer to find [0 to "<< RAND_MAX << "]: ";
cin >> searchVal;
if (AsmFindArray(searchVal, array, ARRAY_SIZE))
{
cout << "Your number was found.\n";
}
else
{
cout << "Your number was not found.\n";
}
return 0;
}
04.MultiplicationTable
subr.asm
; Multiplication Table program (subr.asm)
; Calls external C++ functions.
INCLUDE Irvine32.inc
askForInteger PROTO C
showInt PROTO C, value:SDWORD, outWidth:DWORD
.data
OUT_WIDTH = 8
ENDING_POWER = 10
intVal DWORD ?
.code
;---------------------------------------------
SetTextOutColor PROC C,color:DWORD
;
; Sets the text colors and clears the console
; window. Calls Irvine32 library functions.
;---------------------------------------------
mov eax,color
call SetTextColor
call Clrscr
ret
SetTextOutColor ENDP
;----------------------------------

最低0.47元/天 解锁文章
1147

被折叠的 条评论
为什么被折叠?



