C++ ulong to class method pointer and back
I'm using a hash table (source code by Google Inc) to store some method pointers defined as:
typedef Object *(Executor::*expression_delegate_t)( vframe_t *, Node * );
Where obviously "Executor" is the class.
The function prototype to insert some value to the hash table is:
hash_item_t *ht_insert( hash_table_t *ht, ulong key, ulong data );
So basically i'm doing the insert double casting the method pointer:
ht_insert( table, ASSIGN, reinterpret_cast<ulong>( (void *)&Executor::onAssign ) );
Where table
is defined as a 'hash_table_t *
' inside the declaration of the Executor class, ASSIGN
is an unsigned long value, and 'onAssign
' is the method I have to map.
Now, Executor::onAssign
is stored as an unsigned long value, its address in memory I think, and I need to cast back the ulong to a method pointer. But this code:
hash_item_t* item = ht_find( table, ASSIGN );
expression_delegate_t delegate = reinterpret_cast < expression_delegate_t > (item->data);
Give开发者_StackOverflow中文版s me the following compilation error :
src/executor.cpp:45: error: invalid cast from type ‘ulong’ to type ‘Object* (Executor::*)(vframe_t*, Node*)’
I'm using GCC v4.4.3 on a x86 GNU/Linux machine.
Any hints?
If I remember correctly, a class method pointer may be larger than a normal function pointer due to implementation details. This would explain why the compiler does not allow this cast – the method pointer wouldn’t fit inside the storage space of a “normal” pointer.
The solution, as I’ve stated above in a comment, is to use a proper C++ hash table implementation that allows arbitrary types via C++ templates.
精彩评论