How to get the sample code for the virtual function address of C++ class member
- 2020-05-27 06:43:19
- OfStack
This paper mainly introduces to you how to obtain the virtual function address of C++ class members related content, to share out for your reference to learn, without saying more, to 1 look at the detailed introduction:
1. GCC platform
The GCC platform can obtain the virtual function address of C++ member using the following method [1] :
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 was compiled in Linux g++ (GCC) 4.8.5.
2. Visual C + + platform
[2] can be obtained 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;
// Use the sample
ShowFuncAddress(Base::f1);
The above code was compiled in VS2015.
3. Get the virtual function address by accessing the virtual function table
The following code can be compiled and run in GCC and Visual C++.
/**********************
@className: The class name
@pObj: Class object address
@index: Virtual function table entry (from 0 Start)
**********************/
void showVtableContent(char* className, void* pObj, int index){
unsigned long* pAddr=NULL;
pAddr=reinterpret_cast<unsigned long*>(pObj);
pAddr=(unsigned long*)*pAddr; // Gets a pointer to the virtual function table
cout<<className<<"'s vtable["<<index<<"]";
cout<<": 0x"<<(void*)pAddr[index]<<endl;
}
// Use examples:
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 first 1 A virtual function Base::f1 The address of the
showVtableContent("Base",&b,1); // Output the first 2 A virtual function Base::f2 The address of the
conclusion
reference
[1]print address of virtual member function
[2] principle analysis of dynamic linkage