获取成员函数的内存地址? [英] Get memory address of member function?

查看:291
本文介绍了获取成员函数的内存地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取C ++中成员函数的绝对地址? (我需要使用它来进行重击.)

How do I get the absolute address of a member function in C++? (I need this for thunking.)

成员函数指针不起作用,因为我无法将它们转换为绝对地址(void *)-我需要知道内存中实际函数的地址,而不仅仅是类型的相对地址. /p>

Member function pointers don't work because I can't convert them to absolute addresses (void *) -- I need to know the address of the actual function in memory, not simply the address relative to the type.

推荐答案

存在一种语法来获取MSVC中成员函数的地址(从MSVC 2005 IMHO开始).但这很棘手.而且,所获得的指针不可能通过常规手段转换为其他指针类型.尽管仍然有一种方法可以做到这一点.

There exists a syntax to get the address of the member function in MSVC (starting from MSVC 2005 IMHO). But it's pretty tricky. Moreover, the obtained pointer is impossible to cast to other pointer type by conventional means. Though there exists a way to do this nevertheless.

这里是例子:

// class declaration
class MyClass
{
public:
    void Func();
    void Func(int a, int b);
};

// get the pointer to the member function
void (__thiscall MyClass::* pFunc)(int, int) = &MyClass::Func;

// naive pointer cast
void* pPtr = (void*) pFunc; // oops! this doesn't compile!

// another try
void* pPtr = reinterpret_cast<void*>(pFunc); // Damn! Still doesn't compile (why?!)

// tricky cast
void* pPtr = (void*&) pFunc; // this works

即使使用reinterpret_cast,常规转换也不起作用,这可能意味着MS不太推荐这种转换.

The fact that conventional cast doesn't work, even with reinterpret_cast probably means that MS doesn't recommend this casting very strongly.

尽管如此,您也可以这样做.当然,这都是与实现有关的,您必须知道适当的调用约定才能进行改进,并具有适当的汇编技巧.

Nevertheless you may do this. Of course this is all implementation-dependent, you must know the appropriate calling convention to do the thunking + have appropriate assembler skills.

这篇关于获取成员函数的内存地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆