GLUT and C ++ Classes

I started using OpenGL some time ago using GLUT. You cannot pass member functions to GLUT functions. (or pointers to members in this regard, although I have not actually considered this option).

I was wondering if there is a “decent” way, or what is the “most worthy” way to solve it? I know you can use static member functions, but not the best way?

I know that there are other libraries, such as SFML, that are written in C ++ and provide an interface based on the C ++ class, but I was wondering what these GLUT features (more precisely, freeglut) are.

+4
source share
2 answers

First, GLUT is not suitable for serious applications. This is for simple graphical demos. And for that it’s wonderful. If you try to do some serious work in GLUT, you will find that you spend a lot of time on your limitations. This limitation is just one of many that you will encounter. GLFW, while still having this limitation (although the next version will not) will generally outperform the serious work of the application.

Secondly, the “most worthy” way to solve it depends on what you do. If you have only one window, then the right solution is just a static function that can include global pointers (or functions that return global pointers) in any class that interests you.

If you have several windows, then you need a global std::map , which displays pointers to an object from the GLUT window identifiers. Then you can get from which window a certain function is called and use the map to forward this call to a specific object that this window represents.

+7
source

Passing member functions for oversaturation or any other library is quite simple. GLUT is looking for a function pointer.

Let the controller be a class with the OnKeyPress member function that we want to send to glutKeyboardFunc. At first, you may be tempted to try something like

 glutKeyboardFunc(&Controller::OnKeyPress); 

Here we pass a pointer to a function, however this is not true since you want to send a member function of this class object. In C ++ 11, you can use the new std :: bind , or if you are using an older compiler, I would recommend boost :: bind . In any case, the syntax is about the same.

 using namespace std::placeholders; // for the _1, _2 placeholders glutKeyboardFunc(std::bind(&Controller::OnKeyPress, &GLInput, _1, _2, _3)); 

From the documentation, it looks like glutKeyboardFunc requires 3 parameters. First, we fix the first memory address of the argument of your object, since its member function, and then we supply 3 placeholders.

For those new to std :: bind, this seems weird, but for those who made object-oriented code in C, it is obvious. The function is actually just a C function and needs a "this" pointer for the class. Binding would not be necessary if the callback was a simple function.

0
source

Source: https://habr.com/ru/post/1369249/


All Articles