使用宏定義内聯彙編
盡管一個宏可以分多行定義,但是在宏展開時時,被展開的的宏在源程式中仍然是被寫在一行當中的。
如果定義宏:
#define GetAddress(ptr, function) _asm{\
mov eax, function\
mov ptr, eax\
}
展開之後為:
_asm{mov eax, function} mov ptr, eax}
顯然這樣的内聯彙編代碼是不能通過編譯的,一條獨立的彙編語句隻能在單獨的一行上。是以我們可以将每一條彙編語句單獨放進一個_asm塊中。
改過之後:
#define GetAddress(ptr, function) _asm{\
mov eax, function}\
_asm{mov ptr, eax}\
一個正确使用宏定義内聯彙編的例子:(擷取一個函數的位址)
#include <iostream>
using namespace std;
#include <Windows.h>
#define GetAddress(ptr, function) _asm{\
mov eax, function}\
_asm{mov ptr, eax}\
class Example
{
public:
char c;
public:
Example()
{
c = 'c';
}
void display()
{
cout<<c<<endl;
}
};
int main()
{
void *p = NULL;
cout<<p<<endl;
//_asm{
// mov eax, Example::display
// mov p, eax
//}
GetAddress(p, Example::display);
cout<<p<<endl;
cout<<(PROC)p<<endl;
return 0;
}