filipot
filipot

Reputation: 176

How to pass data to glutTimerFunc?

#include <gl/freeglut.h>

void Keyboard(int value){

    glutTimerFunc(33,Keyboard,0);
}

int main(int argc, char **argv){
   glutTimerFunc(33,Keyboard);
}

Is there any way to pass data from the main function to the keyboard function without having to use global variables? It seems like the function glutTimerFunc only allows functions with the signature (int value) which seems very restrictive.

Upvotes: 0

Views: 672

Answers (2)

datenwolf
datenwolf

Reputation: 162367

so is there another way to get the data into another funcion without having them to be global?

Like other people already suggested: Don't use GLUT. GLUT never was meant to be the foundation of serious application. It's a small framework meant for small OpenGL tech demos. The problem you're running into is that C and C++ lack a concept called "closures", or sometimes also called "delegates". Other languages have them and in fact when you use the GLUT bindings in those languages you don't experience the problem.

Since C/C++'s lack of closures is so prominent a small library (that does crazy but genius things internally) has been written, that allows it, to create closures in C. It's called ffcall, unfortunately seems to be unmaintained, but is in use by projects as the GNU Common Lisp and Scheme compilers.

I wrote about using ffcall already in the StackOverflow answers https://stackoverflow.com/a/8375672/524368 and https://stackoverflow.com/a/10207698/524368

Upvotes: 2

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

You can use a trick: pass a pointer to the object as value, after casting it to int:

i instance;
keyboard((int)&i);

If you need to call the function with the timer, consider the fact that when a function ends all the object in the stack are deallocated. So in this case you should allocate the object with new, and always have a handle to it in the case you need to deallocate it.

It's very tricky, I know. If you can switch to another library do it.

Upvotes: 0

Related Questions