gpt4 book ai didi

c++ - 检测特定虚函数的 vtable 索引/序号(使用 Visual C++)

转载 作者:太空狗 更新时间:2023-10-29 19:38:13 28 4
gpt4 key购买 nike

关于我的问题:Detect the the vtable offset of a specific virtual function (using Visual C++) :

给定:

struct A 
{
virtual void a() {}
virtual void b() {}
virtual void c() {}
};

如何在 Visual C++ 中编写一个函数(可能是不可移植的),这样:

int x = GetVtableIndex(&A::a); //returns 0
int x = GetVtableIndex(&A::b); //returns 1
int x = GetVtableIndex(&A::c); //returns 2

我想这样做的原因在链接的问题中。

最佳答案

受imre的回答启发,如果你只是想知道vtable的总大小;即,有多少虚函数,这可能有效。此方法不实例化类。

template <typename T>
int VTableSize()
{
class VTableCounter
{
public:
virtual int Get1() { return 0; }
virtual int Get2() { return 1; }
virtual int Get3() { return 2; }
// ... 994 more ...
virtual int Get998() { return 997; }
virtual int Get999() { return 998; }
virtual int Get1000() { return 999; }
};

class A : public T
{
public:
virtual int LastVirtual() {return -1;}
};

VTableCounter vt;
return reinterpret_cast<A*>(&vt)->LastVirtual();
}

请注意,我没有使用 Boost.PP,因为据我所知它被限制为 256。你应该能够使用 vim 宏或其他东西来获得任意数量的虚拟。但是,如果使用多重继承或虚拟继承,它可能会给出不正确的值。

关于c++ - 检测特定虚函数的 vtable 索引/序号(使用 Visual C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635212/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com