I need to verify the code of a virtual member function in my other code. So how do I get a pointer that points to the correct code?
class MyInterface {
public:
virtual void VirtualMethod() = 0;
};
class MyImplementation : public MyInterface {
private:
int m_value;
public:
MyImplementation() : m_value(0) { }
virtual void VirtualMethod() {
m_value = 1;
}
};
void main(int argc, char* argv[])
{
MyInterface* pInterface = new MyImplementation();
// In my real code on the following line, we do not have access to the declaration of MyImplementation
unsigned int* pFunctionPointer = (unsigned int*)pInterface->VirtualMethod;
// Now we want to access the compiled code of MyImplementation::VirtualMethod.
printf("0x%08x\n", *pFunctionPointer);
}
In my actual code, I do not have access to MyImplementation declaration at all from the "main" function, if you get my drift.
Here's a little bit of code that I hacked up, which (in g++ 4.6.3) appears to give the expected results.
However, before I get downvotes simply because I'm trying to solve an unsolvable probel, this is absolutely relying on "undefined behaviour". Since the standard doesn't even go into how virtual methods are supposed to be implemented with regards to vptr, vtable, etc, there is no way that you can actually implement this without knowing what the compiler does - and of course, a new version, even in a minor revision, or using different compile options of compiler may change this (e.g. debug mode vs release mode could be different - but that would make it hard to mix debug and release or mix code compiled with old and new compilers)
#include <iostream>
using namespace std;
class A
{
public:
virtual void f();
};
class A2
{
public:
virtual void g();
};
class B: public A, public A2
{
public:
virtual void f();
virtual void g();
};
void print_my_addr(const char *name)
{
cout << "Address of " << name << "=" <<
__builtin_return_address (0) << endl;
}
void A::f()
{
print_my_addr(__FUNCTION__);
}
void A2::g()
{
print_my_addr(__FUNCTION__);
}
void B::f()
{
print_my_addr(__FUNCTION__);
}
void B::g()
{
print_my_addr(__FUNCTION__);
}
// p: pointer to a class object to inspect.
// base_number: which base-class to inspect. 0 = first baseclass
// func_no: function number within the baseclass.
// returns the address as a intptr_t
intptr_t findvirt(A *p, int base_number, int func_no)
{
intptr_t **vptr = reinterpret_cast<intptr_t**>(p);
intptr_t *vtable = vptr[base_number];
return vtable[func_no];
}
int main()
{
A a;
B b;
cout << hex << "Address of A::f()" << findvirt(&a, 0, 0) << endl;
a.f();
cout << hex << "Address of B::f()" << findvirt(&b, 0, 0) << endl;
b.f();
cout << hex << "Address of B::g()" << findvirt(&b, 1, 0) << endl;
}
Related
thanks in advance for your support.
I'm using C++11 and I want to store public member functions of some classes for later use as callback functions; e.g. I want to store some functions that matches this template: void(classname::*)(void). As far as I know, I have to store their objects too, It's fine. For example:
// PSEUDO CODE
class A {
public:
void myfunc() {}
}myobj;
class B {
public:
void myfunc2() {}
}myobj2;
/* storing */
mystorageclass storage;
storage.push(&myobj, &A::myfunc);
storage.push(&myobj2, &B::myfunc2);
/* call them back */
(storage[0].object->*(storage[0].callback))();
(storage[1].object->*(storage[1].callback))();
Is there any safe and generic way to do that? Actually I've found a way, but I'm not sure how much it's portable across processors or compilers.
//test.cpp - compiled with: g++ test.cpp -o test -std=c++11
#include <iostream>
#include <vector>
class A {
public:
void myfunc() { std::cout << "Test A::myfunc()" << std::endl; }
}myobj;
class B {
public:
void myfunc2() { std::cout << "Test B::myfunc2()" << std::endl; }
}myobj2;
struct Callback {
void* object;
void(* method)(void*);
};
std::vector<Callback> callbackList;
template<typename FunctionPtr>
void add(void* object, FunctionPtr fptr) {
Callback cb;
cb.object = object;
cb.method = (void(*)(void*))(*(void**)(&fptr));
callbackList.push_back(cb);
}
int main() {
//add to list for later use
add(&myobj, &A::myfunc);
add(&myobj2, &B::myfunc2);
//call them back
callbackList[0].method(callbackList[0].object);
callbackList[1].method(callbackList[1].object);
}
And another way to do; I feel this is much more safe:
//test2.cpp - compiled with: g++ test2.cpp -o test2 -std=c++11
#include <iostream>
#include <vector>
class A {
public:
void myfunc() { std::cout << "Test A::myfunc()" << std::endl; }
}myobj;
class B {
public:
void myfunc2() { std::cout << "Test B::myfunc2()" << std::endl; }
}myobj2;
struct Callback {
struct A;
A* object;
void(A::* method)();
void call() {
(object->*method)();
}
};
std::vector<Callback> callbackList;
template<typename FunctionPtr>
void add(void* object, FunctionPtr fptr) {
Callback cb;
cb.object = (Callback::A*)object;
cb.method = (void(Callback::A::*)())(fptr);
callbackList.push_back(cb);
}
int main() {
//add to list for later use
add(&myobj, &A::myfunc);
add(&myobj2, &B::myfunc2);
//call them back
callbackList[0].call();
callbackList[1].call();
}
Does these usages are safe? Or what do you suggest instead of these.
Thanks.
Replace Callback with std::function<void()>.
Replace add with
template<class T, class R, class U>
void add(T* object, R(U::*ptr)()) {
Callback cb = [object, ptr]{ object->ptr(); };
callbackList.push_back(cb);
// or just
// callbackList.push_back([object, ptr]{ object->ptr(); });
}
note that this supports passing in pointers-to-parent member functions, and callbacks that do not return void and discarding the result.
std::function stores a generic "call this later". You pass a type compatible with the return value, and args compatible with what you want to call later, in the template signature argument of std::function<signature>. In this case, <void()>.
Problem with the second version
In the line
cb.method = (void(*)(void*))(*(void**)(&fptr));
you are casting a function pointer to void**. I am not sure that is supported by the standard. My guess is it is not. I know casting a function pointer to void* is not supported by the standard. See Print an address of function in C++, g++/clang++ vs vc++ , who is rght? for details.
And then, you proceed to use:
callbackList[1].method(callbackList[1].object);
This relies on conventions used by a compiler to pass this as the first hidden argument when calling a member function of a class. There is no guarantee that the method is used by all compilers. The standard does not explicitly state that.
Problem with the third/last version
You are using:
cb.object = (Callback::A*)object;
cb.method = (void(Callback::A::*)())(fptr);
regardless of whether the object type is A or B. This is cause for undefined behavior. The standard does not support casting of an object pointer to any old pointer type.
A Cleaner Version
Use a base class for Callback.
struct Callback {
virtual ~Callback() = 0;
virtual void call() = 0;
};
Then, use a class template for the real Callbacks.
template <typename T>
struct RealCallback : public Callback
{
RealCallback(T* obj, void (T::*m)(void)) : object(obj), method(m) {}
virtual void call()
{
(object->*method)();
}
T* object;
void (T::*method)();
};
With this, you won't be able to store a list of Callback objects but you can store a list of shared_ptr<Callback>s.
std::vector<std::shared_ptr<Callback>> callbackList;
Here's a complete program that does not rely on any ugly casts and works perfectly.
//test.cpp - compiled with: g++ test.cpp -o test -std=c++11
#include <iostream>
#include <vector>
#include <memory>
class A {
public:
void myfunc() { std::cout << "Test A::myfunc() on " << this << std::endl; }
}myobj;
class B {
public:
void myfunc2() { std::cout << "Test B::myfunc2() on " << this << std::endl; }
}myobj2;
struct Callback {
virtual void call() = 0;
};
template <typename T>
struct RealCallback : public Callback
{
RealCallback(T* obj, void (T::*m)(void)) : object(obj), method(m) {}
virtual void call()
{
(object->*method)();
}
T* object;
void (T::*method)();
};
std::vector<std::shared_ptr<Callback>> callbackList;
template<typename T>
void add(T* object, void (T::*fptr)()) {
RealCallback<T>* cb = new RealCallback<T>(object, fptr);
callbackList.push_back(std::shared_ptr<Callback>(cb));
}
int main() {
//add to list for later use
add(&myobj, &A::myfunc);
add(&myobj2, &B::myfunc2);
std::cout << "myobj: " << &myobj << std::endl;
std::cout << "myobj2: " << &myobj2 << std::endl;
//call them back
callbackList[0]->call();
callbackList[1]->call();
}
Update, in response to comment by Yakk
I think Yakk's suggestion makes sense. You can remove the classes Callback and RealCallback with
using Callback = std::function<void()>;
std::vector<Callback> callbackList;
Then, add can be simplified to:
template<class T>
void add(T* object, void(T::*ptr)()) {
callbackList.push_back([object, ptr]{ (object->*ptr)();});
}
With those changes, main needs to be slightly updated to:
int main() {
//add to list for later use
add(&myobj, &A::myfunc);
add(&myobj2, &B::myfunc2);
std::cout << "myobj: " << &myobj << std::endl;
std::cout << "myobj2: " << &myobj2 << std::endl;
// Updated. Can't use callbackList[0]->call();
//call them back
callbackList[0]();
callbackList[1]();
}
Try with std::function or std::bindboth of them need to keep the reference to the instance:
#include <string>
#include <iostream>
#include <functional>
using namespace std;
class MyClass
{
int _value;
public:
MyClass(int value)
{
_value = value;
}
void food()
{
cout << "Foo is doing something whit value: " << _value << endl;
}
void bar()
{
cout << "Bar is doing something whit value: " << _value << endl;
}
};
int main()
{
MyClass* c1 = new MyClass(1);
MyClass* c2 = new MyClass(2);
cout << "Using 'std::function':" << endl;
std::function<void(MyClass&)> food = &MyClass::food;
std::function<void(MyClass&)> bar = &MyClass::bar;
food(*c1);
bar(*c1);
food(*c2);
bar(*c2);
cout << "Using 'std::bind':" << endl;
auto foodBind = std::bind(&MyClass::food, std::placeholders::_1);
auto barBind = std::bind(&MyClass::bar, std::placeholders::_1);
foodBind(*c1);
barBind(*c1);
foodBind(*c2);
barBind(*c2);
system("PAUSE");
};
the Output is:
I know this question is already answered. But I just want to confirm what I understand.
Here is my snippet code. It comes from this.
#include <iostream>
using namespace std;
class Base
{
void a() { cout << "a "; }
void c() { cout << "c "; }
void e() { cout << "e "; }
// 2. Steps requiring peculiar implementations are "placeholders" in base class
virtual void ph1() = 0;
virtual void ph2() = 0;
public:
// 1. Standardize the skeleton of an algorithm in a base class "template method"
virtual ~Base() = default;
void execute()
{
a();
ph1();
c();
ph2();
e();
}
};
class One: public Base
{
// 3. Derived classes implement placeholder methods
/*virtual*/ void ph1() { cout << "b "; }
/*virtual*/ void ph2() { cout << "d "; }
};
class Two: public Base
{
/*virtual*/ void ph1() { cout << "2 "; }
/*virtual*/ void ph2() { cout << "4 "; }
};
int main()
{
Base *array[] =
{
&One(), &Two()
};
for (int i = 0; i < 2; i++)
{
array[i]->execute();
cout << '\n';
}
}
When I compiled, it gives the error as the title:
error: taking address of temporary [-fpermissive]
&One(), &Two()
error: taking address of temporary [-fpermissive]
&One(), &Two()
So, I try to find in the internet. And as they said:
&A() is creating a temporary object which gets destructed on exit of the full expression automagically...
When I changed error line
&One(), &Two()
to
new One(), new Two()
Then, it works.
But, how I make the origin code works like the author wrote? Should I use delete like
delete array[i];
With modern C++ features (11 and above) you can handle such polymorphic arrays with std::vector<std::unique_ptr<Base>>. vector allows automatic destruction and extension, and unique_ptr will destroy the object on its own destruction:
std::vector<std::unique_ptr<Base>> array;
array.emplace_back(new One());
array.emplace_back(new Two());
for(auto &p : array)
p->execute();
// no explicit cleanup is required here
You can choose other smart pointer classes as vector's elements, or even use std::array as fixed size container, but general idea is same for all approaches:
Try not to handle memory management manually, use STL primitives for
such low-level actions.
I am building an interface, where it would be a little bit inconvenient to use separate variables to access individual interfaces, it would be great if somehow I could create a union of the two.
In a file:
struct A{
virtual int auu() { return 41; }
};
struct B{
virtual int boo() { return 43; }
};
In another file:
#include <path to A, B>
struct C : public A, public B{
int auu() { return 20; }
int boo() { return 22; }
};
And another file:
#include <declaration of A and B, but not C>
void doSth(A* a)
{
B * b = dynamic_cast<B*>(a);
/* I can only call auu with a */
a->auu();
/* I can only call boo with b */
b->boo;
/* Something like this would be ideal: */
<??? type> * C_interface = dynamic_interface_cast<B*>(a)
C_interface->auu();
C_interface->boo();
}
So is there to call both auu and boo through only one pointer variable and without the knowledge of C's implementation (not casting it to )? Also I'd like to avoid creating inheritance hierarchy that is NOT in connection with class C.
Probably the answer is no, however I'm curious if an idea like this has come up from the side of the language developers because to my primitive mind it's not a so far fetched idea.
EDIT:
In real, A and B are abstract. A is a Simulation object that has methods like size() and length(). B is an IO interface, implementing getters and setters, but it doesn't know about sizes so I have to use both interfaces in many calculations. C is a specialized Simulation that implements the former 2.
EDIT:
I rewrote the question, maybe it actually makes sense now.
I'll ilustrate the point I made in my comment. It's perfectly legal to cast between siblings, as long as the actual object is derived from both.
#include<iostream>
using namespace std;
struct A{
virtual int auu() { return 41; }
};
struct B{
virtual int boo() { return 43; }
};
struct C : public A, public B{
int auu() { return 20; }
int boo() { return 22; }
};
void take_B(B* bp)
{
cout << bp->boo() << endl; // expected
cout << "(The base class would say "
<< bp->B::boo() << ")" << endl; // base class implementation
A *ap = dynamic_cast<A*>(bp);
if(!ap)
{
cerr << "weird, this cast should be possible!" << endl;
}
else
{
cout << ap->auu() << endl; // should work
cout << "(The base class would say "
<< ap->A::auu() << ")" << endl; // base class implementation
}
}
int main()
{
C c;
take_B(&c);
cout << endl << "... and again:" << endl;
// just to clarify: The actual pointer type is irrelevant.
B *bp = &c;
take_B(bp);
return 0;
}
#include <iostream>
using namespace std;
class animal
{
public:
void breathe()
{
cout << "breathe!" << endl;
}
int height;
};
class fish : public animal
{
public:
void breathe()
{
cout << "fish breathe!" << endl;
}
int weight;
};
int main()
{
animal *p_animal = new animal();
fish *p_fish = (fish *)p_animal;
p_fish->breathe();
p_fish->weight = 2;
cout << p_fish->weight; //I new a animal instance,but why does it has weight property?
int temp;
cin >> temp;
}
As various commenters have pointed out, you're tricking the compiler into letting you do this.
The key line is
fish *p_fish = (fish *)p_animal;
This line basically forces the compiler to accept that whatever p_animal was pointing to, it's now pointing to a fish.
If you are able to access the properties there, then it's basically chance, and a different compiler might give you different results.
If you had written
fish *p_fish = p_animal;
Then compiler would have complained.
Some side comments on your code.
In this example, you probably want virtual functions. See this modification of your code with some comments :
#include <iostream>
class Animal
{
public:
virtual ~Animal() {} // Always define virtual destructor in this case
virtual void breathe() const // This fonction doesn't modify the object
{ // then, add 'const' at the end
std::cout << "breathe!" << std::endl;
}
unsigned int height; // An animal can't have a negative height ;-)
// then, use an unsigned type.
};
class Fish : public Animal
{
public:
virtual ~Fish() {}
virtual void breathe() const
{
std::cout << "fish breathe!" << std::endl;
}
unsigned int weight;
};
int main()
{
Animal* p_animal = new Animal; // Don't put () for empty constructor
Animal* p_fish = new Fish;
p_animal->breathe(); // this prints "breathe!"
p_fish->breathe(); // this prints "fish breathe!" even if the pointer is
// an pointer to Animal. It's the behaviour of virtual
// functions : when the code is executed, the real type
// is checked and the corresponding function is called.
p_fish->height = 10; // This works
// p_fish->weight = 5; // This doesn't compile, it's an pointer to Animal
Fish* p_real_fish = dynamic_cast<Fish*>(p_fish);
p_real_fish->height = 10; // This works
p_real_fish->weight = 5; // This works too
delete p_animal; // Don't forget to release the memory !
delete p_fish;
}
I hope this can help you.
Can the vtable offset of a specific virtual function be inspected?
Why? I'd like to be able to detect unintentional binary compatibility breaks (see http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B for what I mean by binary compatibility).
I'm aware of the undocumented and unsupported technique of "/d1reportSingleClassLayout" (http://blogs.msdn.com/b/vcblog/archive/2007/05/17/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022.aspx), and I plan to use this technique, but I'd like to also use some simple compile time or run time checks if possible.
Inspired by Jerry's answer, I managed to write up this function that can do the same thing for any function signature:
#include <iostream>
struct A
{
virtual void a() {}
virtual void b() {}
virtual void c() {}
};
template <class T>
int SeeBits(T func)
{
union
{
T ptr;
int i;
};
ptr = func;
return i;
}
int main()
{
int i = SeeBits(&A::a);
int j = SeeBits(&A::b);
int k = SeeBits(&A::c);
std::cout << i << " " << j << " " << k << std::endl;
return 0;
}
It's ugly, non-portable, crufty, etc., but maybe something on this general order would be useful:
#include <iostream>
struct A {
virtual void a() {}
virtual void b() {}
virtual void c() {}
};
int main() {
A a;
typedef void (A::*ptr)();
union see_bits {
ptr p;
int i;
};
see_bits x, y, z;
x.p = &A::a;
y.p = &A::b;
z.p = &A::c;
std::cout << x.i << "\n";
std::cout << y.i << "\n";
std::cout << z.i << "\n";
return 0;
}
To be a bit more portable, you should probably use an array of unsigned char as the second element of the union -- printing that out in a meaningful manner will add a bit more work that I'll leave to you (at least for now).
There's a good example here. Mind though that you won't be able to retrieve function name, just the address/offset.