汇编实验

汇编实验

C/C++中调用汇编的函数

汇编实现搜索的IndexOf函数
对应第十基础篇

IndexOf.asm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
.586
.model flat, C

IndexOf PROTO,
searchVal: DWORD, arrayPtr: DWORD, count: DWORD

.code
IndexOf PROC USES ecx esi edi,
searchVal:DWORD, arrayPtr:DWORD, count:DWORD
;
;对32位整数数组执行线性搜索,
;EAX返回该数值的索引位置,否则返回-1
;--------------------------------------
NOT_FOUND = -1

mov eax, searchVal
mov ecx, count
mov esi, arrayPtr
mov edi, 0
L1:
cmp [esi+edi*4], eax
je found
inc edi
loop L1
NotFound:
mov eax, NOT_FOUND
jmp short Exit

Found:
mov eax, edi
Exit:
ret
IndexOf ENDP
END


C++中调用该函数

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <time.h>

extern "C" long IndexOf(long n, long array[], unsigned count);
using namespace std;
int main()
{
const unsigned ARRAY_SIZE = 100;
const unsigned LOOP_SIZE = 10;
const char* boolstr[] = { "false", "true" };

long array[ARRAY_SIZE];
for (unsigned i = 0; i < ARRAY_SIZE; i++){
array[i] = rand();
}
long searchVal;
time_t startTime, endTime;
cout << "Enter an integer value to find: ";
cin >> searchVal;
cout << "Please wait......\n";

//测试汇编函数
time(&startTime);
int count = 0;

for (unsigned i = 0; i < LOOP_SIZE; i++){
count = IndexOf(searchVal, array, ARRAY_SIZE);
}
bool found = (count != -1);

time(&endTime);
cout << "Elapsed ASM time: " << long(endTime - startTime)
<< " seconds. Found = " << boolstr[found] << endl;

return 0;
}

好了,我们的代码就绪了,那,咋链接起来呢?
配置如下:
右键汇编的文件
配置1
打开属性页
命令行填写:ml /c /coff %(fileName).asm
输出填写:%(fileName).obj;%(OutPuts)
配置2

一个C的代码

1
2
3
4
5
6
7
8
int sumarray(int array[], int count){
int i;
int sum=0;
for(i=0;i<count;i++){
sum+=array[i];
}
return sum;
}

汇编代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
sumarray:
push ebp
mov ebp,esp
sub esp,0D8h
push ebx
push esi
push edi
lea edi,[ebp-0D8h]
mov ecx,36h
mov eax,0CCCCCCCCh
rep stos dword ptr es:[edi]
mov ecx,offset _CAC8CD7F_consoleapplication2@cpp (013DC002h)
call @__CheckForDebuggerJustMyCode@4 (013D1208h)
mov dword ptr [sum],0
mov dword ptr [i],0
jmp sumarray+41h (013D1731h)
mov eax,dword ptr [i]
add eax,1
mov dword ptr [i],eax
mov eax,dword ptr [i]
cmp eax,dword ptr [count]
jge sumarray+5Ah (013D174Ah)
mov eax,dword ptr [i]
mov ecx,dword ptr [array]
mov edx,dword ptr [sum]
add edx,dword ptr [ecx+eax*4]
mov dword ptr [sum],edx
jmp sumarray+38h (013D1728h)
mov eax,dword ptr [sum]
pop edi
pop esi
pop ebx
add esp,0D8h
cmp ebp,esp
call __RTC_CheckEsp (013D1212h)
mov esp,ebp
pop ebp
ret

调试方法:
调试 -> 右键 ->转到反汇编(go to disassembly)
注意:需要在设置里勾选一项:启用地址级调试
工具菜单 -> 选项 -> 调试

Author

Ctwo

Posted on

2019-08-10

Updated on

2020-10-25

Licensed under

Comments