关于通过成员函数指针来获得成员函数地址的方法确实比较困难。它的困难点在于必须绕过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;
}
获取成员函数地址的方法
最新推荐文章于 2024-02-17 15:41:45 发布