class members in static function

This might have been discussed to death before, but I haven't been able to find a good solution yet.

I'm trying to create a small library which works on top of OpenGL and GLUT, like a barebones graphics-library. It contains a SceneManager-class which handles all the gl/glut-calls. The problem is that several of the glut-callbacks are required to be in typical C-style, thus not accepting functions that are members of objects. I realized that making the function static would solve that problem, but now my problem is that the callback functions need to access member of the class!

So basically my question is: is there a good way of accessing the members of a class in a static function in the same class?
There is no way of accessing the members from a static function since you would not know which instantiation of the class you want to access the member data of.

I suggest dividing the library into two: The fundamental GLUT stuff which will be static and there will be only one instance of (since there is only one main window). Maybe call this 'OutputDevice' or something. And then a 'Window' class curresponding to a GLUT subwindow. You can have more than one of these and so they could have their own instance variables.

The 'Window' objects can hold a reference to the 'OutputDevice' object.
callbacks usually give you a 'user data' pointer in the form of a void* which can be used to pass an instance of your class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyClass
{
public:
  void ActualCallback()
  {
    // do stuff here
  }

  static void StaticCallback(void* userdata)
  {
    (reinterpret_cast<MyClass*>(userdata))->ActualCallback();
  }

  void Foo()
  {
    // now give it 'this' as the user data
    take_my_callback( &MyClass::StaticCallback, this );
  }
};
The OpenGL callbacks don't take a context pointer. I couldn't think of a solution that's as fast as C.
The OpenGL callbacks don't take a context pointer.


Really? o_O

That's insane.
Check out the example at the end of the page.
http://www.opengl.org/sdk/docs/man/xhtml/gluTessCallback.xml
Thanks guys:) Disch: I know, right? It's because it's a C-api, but still it's annoying :p

kbw, thanks for the link:)

I sort of went around the issue by making new callback outside of the class which does nothing other than call the function in the class that was supposed to be the callback. This means however that I will need to have a global instance of the class (but this isn't so bad).
Last edited on
The only alternative to a global pointer that I could think of would be to try to capture the context somehow (thread, object instance ...), bu that would require a lookup, which is not really acceptable. I'd go with the global pointer until it proved to be problematic.
Yeah, now that I think about it, it makes sense to have a global "default scenemanager" :)
Topic archived. No new replies allowed.