Home > Back-end >  Can i cast method pointer to long(int, size_t)
Can i cast method pointer to long(int, size_t)

Time:03-17

My problem is i need to represent a pointer to class's method like integer number. So it's not problem with functions, for example void (*func)() easy cast to number, but when i trying to cast void (&SomeClass::SomeMethod) to integer with any ways compiles says it's impossible

C-style cast from 'void(ForthInterpreter::*)()' to long is not alowed

I tried (size_t)&ForthInterpreter::CodeFLiteral, static_cast<size_t>(&ForthInterpreter::CodeFLiteral) but i got the same errors. Should to suppose there is a principal differense between pointer to function and method but what is it? And how can i cast it succesfully? I use clang with C 11 version.

CodePudding user response:

for example void (*func)() easy cast to number

No it's not, it just looks like it on your specific machine. There are systems where a pointer is represented as two internal values, for example read about far pointers.

Not to mention the 64-bit problems you're inviting, long is different types in x64 on gcc and cl for example, two very main-stream compilers.

when i trying to cast void (&SomeClass::SomeMethod) to integer with any ways compiles says it's impossible

Absolutely, because not only a class member pointer has the same problem as above, but it absolutely requires a pointer to the object instance itself (usually passed as a register, and again usually ecx or rcx). There's no way you can represent that in a more portable way than a pointer to the correct type.

i need to represent a pointer to class's method like integer number

No you don't, you just want to. There's a difference there. The solution is to adapt to what is possible instead.

CodePudding user response:

A pointer-to-member is not just a simple pointer, it is much more complex. Depending on compiler implementation, it could be 2 pointers, one to the object and one to the method. Or it could be an object pointer and an offset into a method table. And so on.

As such, a pointer-to-member simply cannot be stored as-is in an integer, like you are attempting to do. So you need to find another solution to whatever problem you are trying to solve by storing a pointer inside an integer.

  • Related