[英]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: 我正在使用哈希表(Google Inc.的源代码)来存储一些定义为:
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. 在Executor类的声明内, table
被定义为' hash_table_t *
', ASSIGN
是一个无符号的long值,而' onAssign
'是我必须映射的方法。
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. 现在, Executor::onAssign
被存储为一个无符号的long值,我认为它的地址在内存中,我需要将ulong强制返回给方法指针。 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. 我在x86 GNU / Linux机器上使用GCC v4.4.3。
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. 正如我在上面的评论中所述,解决方案是使用适当的C ++哈希表实现,该实现允许通过C ++模板使用任意类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.