第二节 2.7内联汇编实现功能
<pre><code class="language-cpp">/*
-----------------------
-----------------------
编写内联汇编,实现功能
-----------------------
-----------------------
*/
int plus(int x, int y, int z)
{
int a = 2;
int b = 3;
int c = 4;
return x + y + z + a + b + c;
}</code></pre>
<hr />
<h2>答案如下:</h2>
<p><img src="https://www.showdoc.com.cn/server/api/attachment/visitfile/sign/f6115abff65af9466e654d4c0005389e" alt="" /></p>
<hr />
<pre><code class="language-cpp">#include <iostream>
#include<Windows.h>
#include<stdio.h>
/*
-----------------------
-----------------------
编写内联汇编,实现功能
-----------------------
-----------------------
int plus(int x, int y, int z)
{
int a = 2;
int b = 3;
int c = 4;
return x + y + z + a + b + c;
}
*/
int __declspec(naked) function(int x, int y, int z)
{
__asm
{
//提升堆栈
push ebp
mov ebp,esp
sub esp,0x40
//保护现场
push edi
push ebx
push esi
//填充缓冲区
lea edi,dword ptr ss:[ebp-0x40]
mov eax,0xcccccccc
mov ecx,0x10
rep stosd
//功能实现
// return x + y + z + a + b + c;
//3个参数:(1, 2, 3)
//3个局部变量:int a = 2 ; int b = 3 ; int c = 4
// [ebp-0x4] ; [ebp-0x8] ; [ebp-0xc]
mov dword ptr ds : [ebp-0x4],2
mov dword ptr ds : [ebp - 0x8],3
mov dword ptr ds : [ebp - 0xc],4
mov eax, dword ptr ds : [ebp + 0x8]
add eax, dword ptr ds : [ebp + 0xc]
add eax, dword ptr ds : [ebp + 0x10]
add eax, dword ptr ds : [ebp - 0x4]
add eax, dword ptr ds : [ebp - 0x8]
add eax, dword ptr ds : [ebp - 0xc]
//还原现场
pop esi
pop ebx
pop edi
//降低堆栈
mov esp,ebp
pop ebp
//返回
ret
}
}
int main()
{
function(1, 2, 3);
system("pause");
return 0;
}</code></pre>