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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值