Call a virtual function from a V-table

Since the entire virtual function in C ++ is stored in a V-table. Overlapping occurs in the case of a virtual function. I want to ask if there is any way by which we can call a virtual function directly from the table, and can also determine which functions the V-table contains.

+7
source share
4 answers

Well, actually you can. I don't care about portability, but in VS you can do it. Assuming that we are building a 32-bit code with VS, the first 4 bytes at the address of the objects are the address of vtable. Studying the header files, we know the order of the methods in the vtable.

Example:

class Base { public: virtual void printMessage() { std::cout << "Base::printMessage()" << std::endl; } }; class Derived : public Base { public: void printMessage() { std::cout << "Derived::printMessage()" << std::endl; } }; int main(int argc, char* argv[]) { Derived d; unsigned int vtblAddress = *(unsigned int*)&d; typedef void(*pFun)(void*); pFun printFun = (pFun)(*(unsigned int*)(vtblAddress)); printFun(&d); return 0; } 

PS I will not ask why you are doing this, but here you have one option :-)

+16
source

The standard does not guarantee that virtual functions are implemented using v-table . So, only if you are sure that this compiler uses v-table , you can find the necessary offset.

+2
source

Probably no. The language does not indicate how virtual sending is carried out, only how it behaves. This is not necessarily implemented using a v-table, and there is no access to a virtual function, except for calling it.

If you need to support only one specific ABI, you can use implementation details along with some dodgy pointers to pointers to map an object to a function pointer just like a virtual submit mechanism does. But you will go beyond a certain language into an unsupported, intolerable territory, so I would definitely recommend rethinking everything that you are trying to do.

+2
source

I would say no at all, because the exact implementation of vtable is platform / compiler specific. If you know how the platform / compiler implements the virtual table and add, you can calculate it by defining the vtable address for a particular class, and then adding the offset of the virtual method.

vtable contains all the virtual methods for the class. You can parse the application to see them.

0
source

All Articles