Skip to main content
GameDev.net gamedev.net
🔒 Locked

Type casting with function pointers and void *

Started by totemokowai Feb 17, 2006 at 8:59 AM 3 replies 550+ views
Original Post
totemokowai
totemokowai
I am attemping to create a debugging system were the user can choose to run any public function within the program. My problem point at the moment is converting a function pointer to a member function into a void * and then back to a member function pointer. I store the this pointer with the void * of the member function, is there a way to use it to convert the void * back into the member function? I know I could use a static member function and not have to worry about it, but that wouldn't really help me. What I am trying to do is this: void *(owl::*ptr2Function)(char *) = NULL; ptr2Function = (void *(__thiscall owl::* )(char *) )memberFunction; where memberFunction is a void * to a member function of the owl class. I also have a void * instance of the owl class that I can type cast back into the owl class that was the this pointer for the instance of the class I want to run the function from. If anyone could help I'd appreciate it.
SiCrane
SiCrane
I'd suggest not using raw function pointers and instead use function objects. In particular, look up boost::function and boost::bind.
Emmanuel Deloget
Emmanuel Deloget
Pointers and pointers to member are totally different entities and you don't want to convert them (a pointer to a member conveys more information than a raw pointer).

SiCrane's idea is probably the best one could have - function objects are a lot easier to handle than these creepy raw pointers and far less dangerous.

Now, if you really want to do weird things, you can use an union. A few month ago, I was searching a way to get the address of the beginning of a method. The results are in this thread. The thread don't speak of the union trick - if you read french, you can get it here (the code is in english, so it should not be that hard; See NonVirtualFunctionAddressFunctorU). Of course, you can discard the "I need the real address, not the fake one" because you don't have to deal with the code itself.

But I still strongly encourage you to use a function objet - they are easier and (more important) more standard.

Regards,
totemokowai
totemokowai
Thanks for the promp responses. For the moment I decided to used a static member function as sort of a helper function to call other member fucntions... unfortunately this means I have to have 2 functions for every operation. I plan to look into the boost function object soon, but needed something up and running now. Thanks again.
Zahlman
Zahlman
If you always know which object you want to invoke the function on, are you sure you need an object in the first place? Is it possible your class (a singleton?) is doing the job that a namespace should (in C++)?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.