Passing 1 argument (pointer) to glutDisplayFunc?

2019-02-15 08:40发布

I have created a virtual class with a basic draw() method which doesn't do anything. The purpose of this is that other classes, shapes and other stuff, which will be able to draw themselves in OpenGL, will inherit this virtual class, allowing me to create an array of pointers to many different classes. The idea behind this was that I was hoping I would be able to pass a pointer to this array into my glutDisplayFunc callback. (This happens to be named drawScene(). Unfortunately I don't seem to be able to pass anything to it, as glutDisplayFunc is designed to take a method which takes no parameters and return nothing.

Is there any way of passing arguments to callback functions, and then any way of passing a pointer into my drawScene function?

(TLDR? See below.)

Essentially I want to be able to do this:

class a{ ... };
void drawScene( a** a_array_pointer){ ... }
glutDisplayFunc(drawScene); // <-- How do I pass an argument into this?

标签: c++ opengl glut
4条回答
forever°为你锁心
2楼-- · 2019-02-15 09:11

Your must parametrize your drawScene with the pointer.

#include <GL/glut.h>

template <void *T>
void drawScene() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    if (T == (void *)0) {
        /* handle no array */
    } else {
        /* handle array */
    }
    glutSwapBuffers();
} 

int main(int argc, char **argv)
{
    glutDisplayFunc(drawScene<(void *)0>);

    return 0;
}

This will only work at compiletime. If you need to change the behavior of drawScene at runtime, you must either recompile another module, load it using LoadLibrary/GetProcAddress and change the pointer, or you must use thread local storage and maybe locks.

It's one of the major flaws of glut, since not having an argument for display makes changing behavior of display at runtime on multiple threads very expensive because you need locks or complicated alternatives.

查看更多
Deceive 欺骗
3楼-- · 2019-02-15 09:23

Unfortunately it's not possible. glutDisplayFunc wants a pointer to a function that doesn't have arguments. See the manual page.

查看更多
再贱就再见
4楼-- · 2019-02-15 09:27

Is there any way of passing arguments to callback functions, and then any way of passing a pointer into my drawScene function?

No. glut is really a C library, and the glutDisplayFunc expects a function pointer as it's parameter. The only way to use variables in that callback, is to make them global or static variables of a class.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-02-15 09:28

This is one of those cases where you should use a global variable.

Also see: How to pass a class method as an argument for another function in C++ and openGL?

查看更多
登录 后发表回答