天天看点

使用宏定义内联汇编使用宏定义内联汇编

使用宏定义内联汇编

尽管一个宏可以分多行定义,但是在宏展开时时,被展开的的宏在源程序中仍然是被写在一行当中的。

如果定义宏:

#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;
}
           
下一篇: C++内联汇编

继续阅读