2

Is there any way to get the exact address of a function member? For example I have :

struct foo
{
    void print() { printf("bla bla bla"); }
};
//////////////////////////////////////////////////////////////
unsigned int address = foo::print;
David G
  • 94,763
  • 41
  • 167
  • 253

2 Answers2

2

You can use the following syntax to declare the pointer to the member function:

typedef void (foo::*address)();
address func = &foo::print;

In order to call non-static member function you will need an existing instance of that class:

(fooInstance.*func)();
nogard
  • 9,432
  • 6
  • 33
  • 53
  • Thanks, but **foo::print** -> **void* address** - Is this possible? –  Jan 29 '13 at 08:29
  • 2
    @xersi read about [function pointers](http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible) and take the advice of Joachim Pileborg about `std::function` and `std::bind`. – PaperBirdMaster Jan 29 '13 at 08:33
  • 2
    @xersi no.`void*` is a data pointer type. Your member function pointer is a code-pointer type. There are, hard as it is to imagine, platforms where they size and/or encodings of the pointer types are different (I can think of two right off the cuff, both from IBM). I suggest you become familiar with [this question and its answers](http://stackoverflow.com/questions/5579835/c-function-pointer-casting-to-void-pointer). Then when you think you need to store a function pointer in a `void*`, *don't*. – WhozCraig Jan 29 '13 at 08:39
  • 3
    @xersi: member function pointers are almost always larger than 'regular' function or data pointers. So no - you can't store a member function pointer in a `void*`, even with casting. – Michael Burr Jan 29 '13 at 08:43
1

I'm not sure what you mean by "exact address". There's certainly no way of putting any address in an unsigned int (which is smaller than a pointer on my machine). For that matter, there's no way of putting a pointer to a function in a void*. Again, I've used machines where pointers to a function were larger than void*. And finally, there's no way of putting a pointer to (non-static) member function into a pointer to function; pointer to member functions are almost always larger. Finally, given:

void (MyClass::*pmf)();
MyClass* p;
(p->*pmf)();

mais call different functions, depending on the contents of p.

So it's not at all clear what you're asking for.

James Kanze
  • 150,581
  • 18
  • 184
  • 329