6

I have a class which has functionality to initialise opengl and run it in separate thread.

My problem is: openGL callbacks such as glutDisplayFunc, glutMotionFunc etc accepts void (*f) void, and I cannot pass class member function.

ways around. 1) I can declare member function as static, but in this case I need to declare all used member variables as static, and end up declaring a whole class as a static.

2) I can use some stand alone function and declare my object as global, but its too bad.

I wonder if there are some ways around so I dont need to make my opengl class static ?? (using c++)

genpfault
  • 51,148
  • 11
  • 85
  • 139
kirbo
  • 1,707
  • 5
  • 26
  • 32

4 Answers4

4

You'll need to create a "thunk" or "trampoline": C API function callbacks into C++ member function code

Community
  • 1
  • 1
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
2

Since the callbacks don't take any parameters, there is not much you can do. One possibility is to create a namespace with functions and a static data member which is your current class. The functions would just forward the function calls to the existing class. This is just basically a slightly cleaner version of your #2.

namespace GLForwader
{
    static MyGLClass* = new myGlClass();

    void glutDisplayFunc() {myGlClass->glutDisplayFunc();}
    void glutMotionFunc() {myGlClass->glutMotionFunc();}
}
KeithB
  • 16,577
  • 3
  • 41
  • 45
0

I've just searched around for this, since I had the same problem when cleaning up and OOP'ing our code. Turns out that the nice stuff like std::bind doesn't work here, but if you're compiling on C++11 anyway you can actually define an anonymous function to wrap your member function.

class Renderer {
  void Start();
  void Render();
}

// ...

void Renderer::Start() {
  // ...
  glutDisplayFunc([](){ Render(); });
}
Michael Nett
  • 375
  • 1
  • 10
0

A simple workaround is :

Declare a global pointer to your class and initialize it in main(), let the callback call a regular method on that instance

MyOGLClass *g_pOGL;

void oglDraw()
{
    if(g_pOGL)
        g_pOGL->oglDraw();
}

void main()
{
    // Init your class
    MyOGLClass o;

    g_pOGL = &o;

    //...

    glutMainLoop();

}

The limitation is you can have only one instance of your class, but for an OpenGL app that isn't so bad as you really need only one anyway...

rep_movsd
  • 6,675
  • 4
  • 30
  • 34