获取成员函数地址的方法

关于通过成员函数指针来获得成员函数地址的方法确实比较困难。它的困难点在于必须绕过C++编译器的类型检查。像VC对成员函数指针类型检查的很严,即使是void*类型都不能转,也无法通过reinterpret_cast、dynamic_cast之类的来转。
因此我这里将采取暴力手段来获取:

#include <iostream>
using namespace std;


class Test
{
public:

void Hello(void)
{
cout << "Hello, world!" << endl;
}

void Hello(int i)
{
cout << "The answer is: " << i << endl;
}
};


template <typename T>
inline unsigned GetMemberFuncAddress(T p)
{
unsigned result;

__asm
{
mov eax, dword ptr [p]
mov dword ptr [result], eax
}

return result;
}


int main(void)
{
void (Test::* p)(void) = &Test::Hello;
void (Test::* q)(int) = &Test::Hello;

(Test().*p)();
(Test().*q)(100);

cout << "The address is: " << p << endl;
cout << "The address is: " << q << endl;

cout << "The address is: 0x" << hex << GetMemberFuncAddress(p) << endl;
cout << "The address is: 0x" << hex << GetMemberFuncAddress(q) << endl;

return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值