viraj viraj - 6 months ago 43
C++ Question

Pointing to a function that is a class member - glfw setKeycallback

I'm writing a glfw app, in which I've wrapped the function callse into a simple class. Im having trouble setting the key callback.
My class is defined as:

class GAME
bool running;
int execute();
void events(int, int);
int loop();
int render();

The execute function is:

int GAME::execute()
glfwOpenWindow(640, 320, 8, 8, 8, 8, 0, 0, GLFW_WINDOW);
running = true;
return 0;

Compiling the following code on Visual Studio 2010, gives the error:

error C3867: 'GAME::events': function call missing argument list; use '&GAME::events' to create a pointer to member

Using &GAME::events gives:

error C2664: 'glfwSetKeyCallback' : cannot convert parameter 1 from 'void (__thiscall GAME::* )(int,int)' to 'GLFWkeyfun'
1> There is no context in which this conversion is possible


There is a C++ syntax for pointing to class member methods but you cannot pass them to a C style API. C understands function calls and every non-static object method, taking your events as an example, looks like this thinking in C terms: void events(void* this, int, int); meaning that every method apart from the standard arguments also gets a this pointer silently passed.

To make your events C compatible make it static void events(int, int);. This way it will follow the C calling semantics - it will not require a this pointer getting passed. You have to also somehow pass your object to this callback in some other manner (if you need this object's data in the callback).