tags:

views:

115

answers:

1

Hi guys, 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);

Gives 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?

+2  A: 

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.

Konrad Rudolph
I should modify a lot of code to use a template hash table class instead of the C implementation, any solution using this one?
Simone Margaritelli
You could use the STL map class or tr1::unordered_map to avoid having to write your own.
Joel
I tried those classes and trust me, the library i'm using is a LOT faster then them .I need a very fast key lookup mechanism for this project.
Simone Margaritelli
PS: Anyway, i'll use std::map for now :)
Simone Margaritelli
@Simone: if I remember correctly, Google also has a collections library for C++. Can’t find it now, though.
Konrad Rudolph
Is std::map really faster than tr1::unordered_map?
Mark B
@Mark: Depends on what you're doing with it.
GMan