Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c++ - Get memory address of member function?

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Here's the example:

// 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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...