4

众所周知,虚函数表指针通常存放在实例的前4个字节中。但是我很好奇虚函数表存放在指定ELF文件的什么位置。我编写了以下程序进行测试,并使用readelf -s a.out命令获取ELF文件的符号表,但找不到“vtable”或类似的东西。

#include <iostream>
#include <stdio.h>
using namespace std;

typedef void (*fun_pointer)(void);
class Test
{
public:
    Test()
    {
        cout<<"Test()."<<endl;
    }
    virtual void print()
    {
        cout<<"Test::Virtual void print()."<<endl;
    }
    virtual void print2()
    {
        cout<<"Test::Virtual void print2()."<<endl;
    }


};

class TestDrived:public Test
{
public:
    TestDrived()
    {
        cout<<"TestDrived()."<<endl;
    }
    virtual void print()
    {
        cout<<"TestDrived::virtual void print()."<<endl;
    }
    virtual void print2()
    {
        cout<<"TestDrived::virutual void print2()."<<endl;
    }

    void GetVtblAddress()
    {
        cout<<"vtbl address:"<<(int*)this<<endl;
    }
    void GetFirstVtblFunctionAddress(void)
    {
        cout<<"First function address in vtbl:"<< (int*)*(int*)this+0;
    }
    void GetSecondVtblFunctionAddress(void)
    {
        cout<<"First function address in vtbl:"<< (int*)*(int*)this+2<<endl;    //my os is 64bit   //linux, if you use 32bit OS, please replace the "this+2" with "this+1"
    }
    void CallFirstVtblFunction()
    {
        fun = (fun_pointer)* ( (int*)*(int*)this+0 );
        fun();
    }
    void CallSecondVtblFunction()
    {
        fun = (fun_pointer)* ( (int*)*(int*)this+2 );  //my os is 64bit   
        //linux, if you use 32bit OS, please replace the "this+2" with "this+1"
        fun();
    }
private:
    fun_pointer fun;   
};


int main()
{
    cout<<"sizeof(int):"<<sizeof(int)<<"sizeof(int*)"<<endl<<sizeof(int*)<<endl;
    fun_pointer fun = NULL;
    TestDrived a;
    a.GetVtblAddress();
    a.GetFirstVtblFunctionAddress();
    a.GetSecondVtblFunctionAddress();
    a.CallFirstVtblFunction();
    a.CallSecondVtblFunction();
    return 0;
}
4

2 回答 2

2

虚拟表存储在 ELF 文件的 .rodata 部分,其对应的段被加载到内存中。

于 2015-01-03T16:50:05.557 回答
0

更正说明:相应段已加载到内存中。-> 相应的段正在将其加载到内存中。因为段是内存中的概念,而不是可执行文件。当人们阅读它以获得帮助时,恐怕会有一些令人困惑的部分。

于 2021-09-01T14:23:38.463 回答