Peter mở ra vấn đề này cũng là vì giới thiệu với các bạn một vài code Inline ASM trong C/C++; với bài này Peter cho các bạn thấy một ví dụ đơn giản như tính tổng của 2 số thực (float) chẳng hạn:
Hay cũng có thể làm như thế này (với số nguyên (int) có thêm các thao tác Trừ, Nhân và Chia):
Hoặc Inline chuẩn:
Vậy các bạn thấy thế nào???
Được sửa bởi peterdrew ngày Sun Sep 05, 2010 3:30 pm; sửa lần 1.
Code:
#include <conio.h>
#include <stdio.h>
float a,b,tong;
int main()
{
printf("Nhap vao so thu nhat, a= ");
scanf("%f",&a);
printf("Nhap vao so thu 2, b= ");
scanf("%f",&b);
_asm
{
fld a
fld b
fadd ST,ST(1)
fstp tong
fwait
}
printf("Tong cua hai so %f va %f la %f",a,b,tong);
getch();
return 0;
}
Hay cũng có thể làm như thế này (với số nguyên (int) có thêm các thao tác Trừ, Nhân và Chia):
Code:
#include <stdio.h>
#include <conio.h>
int Cong(int x, int y)
{
__asm
{
mov eax,x;
mov ebx,y;
add eax,ebx;
mov x,eax;
}
return x;
}
int Tru(int x, int y)
{
__asm
{
mov eax,x;
mov ebx,y;
sub eax,ebx;
mov x,eax;
}
return x;
}
int Chia(int x, int y)
{
__asm
{
mov eax,x;
mov ecx,y;
sub edx,edx;
div ecx;
mov x,eax;
}
return x;
}
int Nhan(int x, int y)
{
__asm
{
mov eax,x;
mov ebx,y;
mul ebx;
mov x,eax;
}
return x;
}
int main ()
{
int func;
int x,y;
bool finish=false;
while (finish==false)
{
printf("1: Cong, 2: Tru, 3: Chia, 4: Nhan\n");
printf("Lua chon:\n");
scanf("%d",&func);
printf("Nhap so hang dau tien:\n");
scanf("%d",&x);
printf("Nhap so hang thu hai:\n");
scanf("%d",&y);
switch(func)
{
case 1:
printf("Tong %d va %d la: ",x,y,Cong(x,y));
break;
case 2:
printf("Hieu %d cho %d la: ",x,y,Tru(x,y));
break;
case 3:
printf("Thuong nguyen %d chia %d la: ",x,y,Chia(x,y));
break;
case 4:
printf("Tich %d va %d la: ",x,y,Nhan(x,y));
break;
}
}
return 0;
}
Hoặc Inline chuẩn:
Code:
extern "C" __declspec(naked) int __stdcall Cong(int x, int y)
{
_asm
{
mov eax, dword ptr [esp+4]
add eax, dword ptr [esp+8]
ret 8
}
}
extern "C" __declspec(naked) int __stdcall Tru(int x, int y)
{
_asm
{
mov eax, dword ptr [esp+4]
sub eax, dword ptr [esp+8]
ret 8
}
}
extern "C" __declspec(naked) int __stdcall Chia(int x, int y)
{
_asm
{
mov eax, dword ptr [esp+4]
cdq
mov ecx, dword ptr [esp+8]
div ecx
ret 8
}
}
extern "C" __declspec(naked) int __stdcall Nhan(int x, int y)
{
_asm
{
mov eax, dword ptr [esp+4]
mul dword ptr [esp+8]
ret 8
}
}
Vậy các bạn thấy thế nào???
Được sửa bởi peterdrew ngày Sun Sep 05, 2010 3:30 pm; sửa lần 1.