C++ 内联汇编方式

内联汇编方式:
内联汇编方式两个作用:
1、程序的某些关键代码直接用汇编语言编写可提高代码的执行效率。
2、有些操作无法通过高级语言实现,或者实现起来很困难,必须借助汇编语言达到目的。
使用方式:
1、_asm块
_asm{汇编语句}
2、_asm语句

 1 #include<iostream>
 2 using namespace std;
 3 void print(){
 4     cout<<"External Function"<<endl;
 5 }
 6 class A{
 7 public:
 8     void print(){
 9         cout<<"A::Member Function"<<endl;
10     }
11 };
12 typedef void(*fun)();
13 int main(){
14     fun p;
15     void *v;
16 
17     v = (void *)&print;
18     p=(fun)v;
19     p();
20     //用内联汇编方式获取类的非静态成员函数的入口地址。
21     _asm{
22         //将A::print的偏移地址送到eax寄存器中
23         lea eax,A::print
24         mov v,eax
25     }
26     p=(fun)v;
27     p();
28     return 0;
29 }

 上述print函数并没有访问类A的成员属性。

在VisualC++中,类的成员函数在调用之前,编译器生成的汇编码
将对象的首地址送入到寄存器ecx中。因此,如果通过内联汇编码
获取了类的非静态成员函数的入口地址,在调用该函数之前,
还应该将类对象的首地址送到寄存器ecx中。只有这样才能保证
正确调用

 1 #include<iostream>
 2 using namespace std;
 3 typedef void(*fun)();
 4 
 5 class A{
 6     int i;
 7 public:
 8     A(){i=5;}
 9     void print(){
10         cout<<i<<endl;
11     }
12 };
13 void Invoke(A &a){
14     fun p;
15     _asm{
16         lea eax,A::print
17         mov p,eax
18         mov ecx,a  //将对象地址送入ecx寄存器
19     }
20     p();
21 
22 }/*
23 void Invoke(A a){
24     fun p;
25     _asm{
26         lea eax,A::print
27         mov p,eax
28         lea ecx,a
29     }
30     p();
31 }*/
32 int main(){
33     A a;
34     Invoke(a);
35 }
原文地址:https://www.cnblogs.com/teng-IT/p/6022993.html