C++ Get address for non-static function
You can get "address" of a non-static member function using the addressof operator. The address that you get will be of type "pointer to member function" (which despite their name, are not pointers). You cannot convert that pointer to member function into an integer.
In C for example I can get function address by
uint64_t ptr = (uint64_t)&MyFunction;
You can achieve the same in C++ although not directly and not on all systems ("not on all systems" also applies to C; your C example won't work on all systems). And it can only be achieved for free functions or static member functions.
In C++, function pointers cannot be directly converted to integers. Only object pointers can be. Converting a function-pointer to pointer-to-void (which is an object pointer) is allowed if the language implementation supports it . As such, following would be valid on such supporting systems:
using Fun = decltype(MyFunction); // not a non-static member function
Fun* function_ptr = &MyFunction;
void* void_ptr = reinterpret_cast<void*>(function_ptr)
std::uintptr_t int_ptr = reinterpret_cast<std::uintptr_t>(void_ptr);
void* void_ptr_back = reinterpret_cast<void*>(int_ptr);
Fun* function_ptr_back = reinterpret_cast<Fun*>(void_ptr_back);
assert(function_ptr == function_ptr_back);
If the system doesn't support this conversion between function pointers and void*
, then the program is safely ill-formed.
Note that this applies only to function pointers, and not to member function pointers. If MyClass::MyFunction
is a non-static member function (edit: and it is in your edited question), then there is no standard way to convert it to an integer.
P.S. Reinterpreting an object pointer as std::uint64_t
is guaranteed to work only on systems where the iteger can represent all pointer values. It may be so at the moment, but for future portability, using std::uintptr_t
is recommended.