Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

c++ - Print address of virtual member function

I am trying to print the address of a virtual member function. If I know which class implements the function I can write:

print("address: %p", &A::func);

But I want to do something like this:

A *b = new B();

printf("address: %p", &b->func); 
printf("address: %p", &b->A::func);

However this does not compile. Is it possible to do something like this, perhaps looking up the address in the vtable at runtime?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Currently there is no standard way of doing this in C++ although the information must be available somewhere. Otherwise, how could the program call the function? However, GCC provides an extension that allows us to retrieve the address of a virtual function:

void (A::*mfp)() = &A::func;
printf("address: %p", (void*)(b->*mfp));

...assuming the member function has the prototype void func(). This can be pretty useful when you want to cache the address of a virtual function or use it in generated code. GCC will warn you about this construct unless you specify -Wno-pmf-conversions. It's unlikely that it works with any other compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...