直接访问 VTABLE 会出现未定义的错误

Accessing VTABLE directily issues undefined error

我正在试验虚拟 table 和虚拟指针。要了解更多信息,我做了以下操作:

  //a simple class
  class X
  {
  public:
       // fn is a simple virtual function
       virtual void fn() { cout << "n = " << n << endl; }
       // a member variable
       int n;
  };

  int main()
  {
     // create an object (obj) of class X
     X *obj = new X();
     obj->n = 10;

     // get the virtual table pointer of object obj
     int* vptr =  *(int**)obj;

     __asm__("mov %eax, obj;");

     // function fn is the first entry of the virtual table, so it's vptr[0]
     ((void (*)()) vptr[0])();

     // the above should be the same as the following
     //obj->fn();

     return 0;
  }

但是编译器给出了以下错误:

/home/OaVTND/cclnoQaK.o: In function 'main': prog.cpp:(.text.startup+0x26): undefined reference to `obj'
collect2: error: ld returned 1 exit status

我不熟悉汇编语言代码。我从其他人的代码中借用了这个。我正在使用 gcc-4.9 和 Centos 7 x64 位服务器。

obj是一个局部变量,它没有链接,没有符号。 只是尝试使您的对象成为全球对象。

只需摆脱内联 asm 并执行

((void (*)(void *)) vptr[0])(&obj);

警告:我假设您 运行 在 gcc Linux x86_64 上,因为其他平台上的 ABI 细节会有所不同。