Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function pointer to integer?

Is it possible to get the virtual address as an integer of a member function pointer?

I have tried.

void (AClass::*Test)();
Test = &AClass::TestFunc;
int num = *(int*)&Test;

But all that does is get me the virtual address of a jmp to the function. I need the actual functions virtual address.

like image 896
user230821 Avatar asked May 28 '10 13:05

user230821


2 Answers

I know this is old, but since there's no meaningful on-the-subject answer, here I go.

Some things need to be taken into account first. Member-function calling convention in C++ is called __thiscall. This convention is almost identical to __stdcall, the only significant difference being that, before the effective call is made, ECX is set to be the pointer this of the object of which's method is called.

To illustrate this and answer your question at the same time, let's say that the class AClass has a member function declared like this: int AClass::myFunction(int a, int b) and that we have an instance of AClass called aClassObject. Here's a rather hackish way to do what you initially asked for AND 'simulate' a AClass::myFunction call on the aClassObject once you obtain the raw pointer:

// declare a delegate, __stdcall convention, as stated above
typedef int (__stdcall *myFunctionDelegate)(int a, int b);
// here's the 'hackish' solution to your question
char myFunctionPtrString[10];
sprintf(myFunctionPtrString, "%d", &AClass::myFunction);
int myFunctionPtr = atoi(myFunctionPtrString);
// now let's call the method using our pointer and the aClassObject instance
myFunctionDelegate myFunction = (myFunctionDelegate)myFunctionPtr;
// before we make the call, we must put a pointer to aClassObject
// in ECX, to finally meet the __thiscall calling convention
int aClassObjectPtr = (int)&aClassObject;
__asm{
     mov ecx, aClassObjectPtr
}
// make the call!
myFunction(2, 3);

And of course, the instance can be any instance of type AClass.

like image 147
Zuzu Corneliu Avatar answered Oct 03 '22 09:10

Zuzu Corneliu


No, member function pointers can have a variety of sizes (from 4-16 bytes or more depending on platform, see the table in the article) and cannot reliably fit inside the space of an integer. This is because virtual functions and inheritence can cause the compiler to store several pieces of information in order to call the correct function, so in some cases there is not a simple address.

like image 24
AshleysBrain Avatar answered Oct 03 '22 09:10

AshleysBrain