This article mainly introduces to you about how to obtain the virtual function address of C++ class member. It is shared for your reference and learning. Without further ado, let’s take a look at the detailed introduction:
platform
The GCC platform can use the following method [1] to obtain the address of C++ member virtual function:
class Base{ int i; public: virtual void f1(){ cout<<"Base's f1()"<<endl; } }; Base b; void (Base::*mfp)() = &Base::f1; printf("address: %p", (void*)(b->*mfp));
The above code is compiled and passed in Linux g++ (GCC) 4.8.5.
C++ Platform
You can obtain [2] by inline assembly, the code is as follows:
#define ShowFuncAddress(function) _asm{\ mov eax, function}\ _asm{mov p,eax}\ cout<<"Address of "#function": "<<p<<endl; //User exampleShowFuncAddress(Base::f1);
The above code was compiled and passed in VS2015.
3. Obtain the virtual function address by accessing the virtual function table
The following code can be compiled and run in GCC and Visual C++.
/****************************** @className: Class Name @pObj: Class object address @index: Virtual function table entry (starting from 0) ******************************/ void showVtableContent(char* className, void* pObj, int index){ unsigned long* pAddr=NULL; pAddr=reinterpret_cast<unsigned long*>(pObj); pAddr=(unsigned long*)*pAddr; //Get the virtual function table pointer cout<<className<<"'s vtable["<<index<<"]"; cout<<": 0x"<<(void*)pAddr[index]<<endl; } //Usage example:class Base{ int i; public: virtual void f1(){ cout<<"Base's f1()"<<endl; } virtual void f2(){ cout<<"Base's f2()"<<endl; } }; Base b; showVtableContent("Base",&b,0); //Output the address of the first virtual function Base::f1showVtableContent("Base",&b,1); //Output the second virtual functionBase::f2Address
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.
References
[1]print address of virtual member function
[2]Analysis of the principle of dynamic linkage implementation