While I can't say definitively whether there is a portable way to do this, I generally recommend making a static wrapper function to provide this type of external access to a class method. Otherwise even if you succeeded you would be creating very tight coupling of the application to that class implementation.
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.
If this is what I suspect it is, just switch off incremental linking. In the mean time, you're getting the right answer.
My other suspicion is that TestFunc
may be virtual
. For virtual functions whose address is taken, VC++ fakes up a little thunk that does the vtable lookup, and gives a pointer to that thunk as the address. (This ensures the correct derived function is found when the actual object is of a more-derived type. There are other ways of doing this, but this allows such pointers to be a single pointer and simplifies the calling code, at the cost of double jump when they're called through.) Switch on assembly language output for your program, and look through the result; it should be clear enough what's going on.
Here, too, what you're getting is the correct answer, and there's no way to find out the address of the "actual" function. Indeed, a virtual function doesn't name one single actual function, it names whichever derived function is appropriate for the object in question. (If you don't like this behaviour, make the function non-virtual.)
If you REALLY need the genuine address of the actual function, you've got two options. The annoying one is to write some code to scan the thunk to find out the vtable index of the function. Then look in the vtable of the object in question to get the function.
(But note that taking the address of a non-virtual function will give you the address of the actual function to call, and not a thunk -- so you'd have to cater for this possibility as well. The types of pointers to virtual functions and pointers to non-virtual functions are the same.)
The easier one is to make a non-virtual function that contains the code for each virtual function, then have each virtual function call the non-virtual function. That gives you the same behaviour as before. And if you want to find out where the code is, take the address of the non-virtual function.
(In either case, this would be difficult to make work well, it would be annoying, and it would be rather VC++-specific -- but you could probably make it happen if you're willing to put in the effort.)