muszę konwertować kilka wskaźników funkcji member aby void*
wskaźników (bo muszę pchnąć je do Lua stos, ale problem nie jest Lua podobne).Wywoływanie C++ wskaźnik funkcji użytkownika: to-pointer zostanie uszkodzona
Robię to za pomocą union
. Ale kiedy konwertuję wskaźniki funkcji składowej na void*
i ponownie, a następnie spróbuję wywołać wskaźnik za pomocą klasy klasy, wskaźnik this
zostanie uszkodzony. Co dziwne, ten problem nie występuje, jeśli skonwertuję wskaźnik void*
z powrotem na wskaźnik funkcji w stylu C ze wskaźnikiem do klasy jako jej pierwszym parametrem.
Oto fragment kodu, który demonstruje 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;
// assign the member function pointer to the first union
conv1.func = &test::tellSomething;
// copy the void* pointers
conv2.ptr = conv3.ptr = conv1.ptr;
// call without conversion
void (test::*func1)() = conv1.func;
(t.*func1)(); // --> works
// call with C style function pointer invocation
void (*func3) (test*) = conv3.func;
(*func3) (&t); // --> works (although obviously the wrong type of pointer)
// call with C++ style member function pointer invocation
void (test::*func2)() = conv2.func;
(t.*func2)(); // `this' is the wrong pointer; program will crash in the member function
return 0;
}
czyli wyjście:
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
Jest to błąd w kompilator (GCC)? Wiem, że konwersja pomiędzy wskaźnikami funkcji void*
i (członkiem) nie jest zgodna ze standardem, ale dziwne jest to, że działa, konwertując void*
na wskaźnik funkcji stylu C.
Czy sprawdziłeś sizeof() swojego memfunptr? W mojej implementacji jest większy niż sizeof (void *) – PlasmaHH