I need to convert some pointers to member functions to pointers void*(because I need to push them to the Lua stack, but the problem is not related to Lua).
I do this with help union. But when I convert the pointers of a member function to void*and vice versa, and then try to call a pointer with an instance of the class, the pointer thiswill get corrupted. Strange, this problem does not occur if I convert the pointer void*back to a pointer to a C-style function with a pointer to the class as the first parameter.
Here is a piece of code that demonstrates the problem:
#include <iostream>
using namespace std;
class test
{
int a;
public:
void tellSomething ()
{
cout << "this: " << this << endl;
cout << "referencing member variable..." << endl;
cout << a << endl;
}
};
int main ()
{
union
{
void *ptr;
void (test::*func) ();
} conv1, conv2;
union
{
void *ptr;
void (*func) (test*);
} conv3;
test &t = *new test ();
cout << "created instance: " << (void*) &t << endl;
conv1.func = &test::tellSomething;
conv2.ptr = conv3.ptr = conv1.ptr;
void (test::*func1) () = conv1.func;
(t.*func1) ();
void (*func3) (test*) = conv3.func;
(*func3) (&t);
void (test::*func2) () = conv2.func;
(t.*func2) ();
return 0;
}
This is the result:
created instance: 0x1ff6010
this: 0x1ff6010
referencing member variable...
0
this: 0x1ff6010
referencing member variable...
0
this: 0x10200600f
referencing member variable...
zsh: segmentation fault (core dumped) ./a.out
(GCC)? , void* (member) , , void* C.