-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
Leonel Flor?n Selles wrote:
Well friends, i’ll going to repeat the question, I have a callback function
where I want to call an other function, and I want do that from SDL_UserEvent,
but what i know is that SDL_UserEvent is an structure that have 4 kind of data
or more
SDL_UserEvent -> type
SDL_UserEvent -> code
SDL_UserEvent -> void * data1
SDL_UserEvent -> void * data2
and the last one i don’t remember, well how using this i can connect this
UserEvent with a function.
In C, you may cast the pointer to the function to a void*, but you must ensure
that when you “recover” the pointer to the function its signature is the same
(see items 766-768 @ http://c0x.coding-guidelines.com/6.3.2.3.html):
#include <stdio.h>
int foo(int bar) { return bar; }
int main()
{
void* function = &foo;
int (*fooz)(int) = function;
printf(“3 == %d\n”, fooz(3));
return 0;
}
In C++, you need to add the (in-)appropriate casts:
#include <stdio.h>
int foo(int bar) { return bar; }
int main()
{
void* function = reinterpret_cast<void*>(&foo);
int (fooz)(int) = reinterpret_cast<int ()(int)>(function);
printf(“3 == %d\n”, fooz(3));
return 0;
}
But that’s like sledgehammering a rose petal. You’re completely foregoing type
safety and it’s a nightmare to debug. And on-top, it doesn’t work for class methods.
One approach is to store instances that adhere to an interface in a vector
somewhere:
#include
struct IEvtCB
{
virtual int bar(void*, void*) = 0;
};
struct EvtCB_1 : public IEvtCB
{
virtual int foo(void*, void*) { return bar; }
};
std::vector<EvtCB_1*> vec;
int main()
{
vec.push_back(new EvtCB_1());
return 0;
}
then find the corresponding instance in the vector and invoke the the method in
question:
/* … */
if (evt.type == SDL_USEREVENT) {
if (evt.user.code > -1) {
IEvtCB& cb = vec[evt.user.code];
int ret = cb.bar(evt.user.data1, evt.user.data2);
}
else {
/* something’s amiss */
}
}
/* … */
Another way is to use a functor (google it) that encapsulates the function or
method call and that you can then store in data1 or data2 and cast back to a
functor later on.
- -- Christopher C. Eineke -- Email: chris at chriseineke.com -*-
- -- Independent Software Developer -- Cell: 1-519-852-3409 -*-
- -- -- Home: 1-226-663-3651 -*-
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEAREKAAYFAkrqWhgACgkQPOmqd0kEEbtvAwCgpVEFBdecm+I97Xc1Dym6bwvZ
J2gAoIv9191GdGVU3n1veJhYRjx2q5Kz
=Zexz
-----END PGP SIGNATURE-----