Is it possible to use non-static function of class for GLUT callback function?

I’ll try to explain what I mean :rolleyes:

Example :

#includes ...

class X {

public:

     X() {}
     ~X() {}

     void myDisplay(void) {}
     static void myDisplayStatic(void) { }

};


X* x;


int main(int argc, char** argv) {
     x = new X();

     glutInit(&argc, argv);
     glutInitDisplayMode(GLUT_RGB |  GLUT_DOUBLE);
     glutInitWindowSize(800, 600);
     glutInitWindowPosition(100, 100);
     win = glutCreateWindow("X");

     // I can use there myDisplayStatic function.
     glutDisplayFunc(myDisplayStatic);

     // BUT!!!
     // Can I use there myDisplay function???
     // Something like
     // glutDisplayFunc((???)myDisplay);

     glutMainLoop();

     return 1;
}

If it’s possible, please, tell me how?

I think it’s not because of the different calling conventions. You know the so called ‘this’ pointer? Think at it as an hidden arg passed to funcs.

This to say I already tried something like that without success, maybe it’s really possible to workaround that but I don’t know how this could be possible without hacks. By this, I mean, an elegant way.

I don’t even know if this is a real need however.

You could try something like this as an alternative:

#includes ...
  
class GlutApp {
public:   
static GlutApp* app;  
GlutApp() { app = this; }     
virtual ~GlutApp() { app = 0; }     
virtual void onDisplay() {}  
static void appDisplayStatic() { 
if( app ) app->onDisplay(); 
}
};
GlutApp* GlutApp::app = 0;
   
class MyApp : public GlutApp {
void onDisplay() {
// draw stuff
}
}

MyApp* x;
int main(int argc, char** argv) {     
x = new MyApp();     
glutInit(&argc, argv);     
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);     glutInitWindowSize(800, 600);     glutInitWindowPosition(100, 100);     
win = glutCreateWindow("X");     
// you could override this static function too.
glutDisplayFunc(x->appDisplayStatic);     
glutMainLoop();     
return 1;
}

You could stuff all the static GLUT notify functions into GlutApp, then override what you need in a particular app, by way of virtual functions. You can have a slick little wrapper that you can reuse. Admittedly, this is a bit “around your ass to your elbow”, but it might come in handy.

Put the pointer-to-member_function into functor and register the functor with GLUT. Functor is just a fancy name for a class that has operator() so it can be called like a function. function pointers

// ville

Put the pointer-to-member_function into functor and register the functor with GLUT. Functor is just a fancy name for a class that has operator() so it can be called like a function.
unfortunately this wont work for glut callbacks. you gotta use a static function. for glut to call a member function it would need an instance of the class.