PDA

View Full Version : Fuction class pointer problem.


IceColdDuke
04-02-2005, 01:26 AM
Im having a problem assigning a class function to a pointer.

Example:
Without a class you could do this:
void myfunc(void)
{

}

void (*my_func)(void);
my_func = mufunc;

How would you do that samething if those functions were inside of a class...even the local class.

rg3
04-02-2005, 08:40 AM
I remember having problems creating pointers to class methods, but I don't remember if they could be solved or not. First you have to take into account the method resides inside a namespace (which can be ommitted if you're referencing it from the namespace itself). But then you have problems because methods have an implicit first parameter, which is the address of the calling object...

So all in all I'm not sure how to do that, I should check the Stroustroup book...

Edit:
http://www.codeproject.com/cpp/FastDelegate.asp

DudeMiester
04-02-2005, 03:20 PM
The reason you can't make a regular function pointer to a class function, is because in order to call the class function you need something to make a "this" address with. So no matter what you have to provide a instance of that class to work with. This is how you do that:

class CBlah
{
public:
void func(){}
};

void (CBlah::* FuncPtr)();

main()
{
FuncPtr=&CBlah::func;

CBlah Test;
Test.*FuncPtr();
(&Test)->*FuncPtr();
}

Of course there are various tricks to get around it, like:

void (* FuncPtr2)();

main()
{
void (CBlah::* Temp)()=&CBlah::func; FuncPtr2=*reinterpret_cast<void(**)()>(&Temp);

//I really hope you didn't use "this" in the function
(*FuncPtr2)();

//But if you did:
CBlah Temp;
_asm lea ecx, [Temp];
(*FuncPtr2)();
}

Now the above method works even for virtual functions, because the compiler will add a thunking function, so when you call the function pointer, you actually call the thunker. This looks up the virtual function from the vtable, and modifies the "this" pointer appropriately, then calls the real function.

This was done with VC++ 7.1 mind you, your results may vary. Many compilers have very different ways of calling functions. Reading the comments in that FastDelagate code will be very helpful!

IceColdDuke
04-02-2005, 05:32 PM
Thanks, thats what I was looking for.