內聯彙編方式:
內聯彙編方式兩個做用:
一、程序的某些關鍵代碼直接用匯編語言編寫可提升代碼的執行效率。
二、有些操做沒法經過高級語言實現,或者實現起來很困難,必須藉助彙編語言達到目的。
使用方式:
一、_asm塊
_asm{彙編語句}
二、_asm語句ios
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 }