首页 > Computer > c++ > vtable function
2012
08-29

vtable function

template<typename T>
const void* void_cast(const T& object)
{
    union Retyper
    {
        const T object;
        void* pointer;
        Retyper(T obj) : object(obj) { }
    };
 
    return Retyper(object).pointer;
}
 
template<typename T, typename M>
const void* getMethodPointer(const T* object, M method) // will work for virtual methods
{
    union MethodEntry
    {
        intptr_t offset;
        void* function;
    };
 
    const MethodEntry* entry = static_cast<const MethodEntry*>(void_cast(&method));
 
    if (entry->offset % sizeof(intptr_t) == 0) // looks like that’s how the runtime guesses virtual from static
        return getMethodPointer(method);
 
    const void* const* const vtable = *reinterpret_cast<const void* const* const* const>(object);
    return vtable[(entry->offset – 1) / sizeof(void*)];
}
 
template<typename M>
const void* getMethodPointer(M method) // will only work with non-virtual methods
{
    union MethodEntry
    {
        intptr_t offset;
        void* function;
    };
 
    return static_cast<const MethodEntry*>(void_cast(&method))->function;
}

最后编辑:
作者:wy182000
这个作者貌似有点懒,什么都没有留下。

留下一个回复