Answer the question
In order to leave comments, you need to log in
How to pass a variable to a function without using global variables?
The openGL(glut) packages have a function of the form:
void glutDisplayFunc( void (*func)( ) )
That is, the function accepts a function of type void with no arguments.
And here's the question.
How to pass a variable to a function (which we pass to glutDisplayFunc) without using global variables?
For example, I wrote a simple program illustrating the problem.
#include <glut.h> //Подключаем библиотеку glut
int WIDTH = 400; //Глобальная переменная ширины
int HEIGHT = 400; //Глобальная переменная высоты
void setPixel(int x, int y) //Функция отрисовки пикселя с координатами (x,y)
{
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void myDisplay() //Функция, которая будет отвечать за рисование в окне
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0, 0, 0);
glPointSize(100);
setPixel(WIDTH / 2, HEIGHT / 2);//Ставим пиксель в центре окна с использованием глобальных переменных
glFlush();
}
void main()
{
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WIDTH, HEIGHT);//Инциализируем размер окна с использованием глобальных переменных
glutCreateWindow("Problem");
glClearColor(1, 1, 1, 1);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, WIDTH, 0, HEIGHT);//Устанавливаем двумерную область просмотра с использованием глобальных переменных
glutDisplayFunc(myDisplay); //Собсвенно вот она - проблема
glutMainLoop();
}
Answer the question
In order to leave comments, you need to log in
assigning a function to a variable, then passing it
void (*fcnPtr)(void) = boo;
glutDisplayFunc( fcnPtr );
Read about functional classes. Those. those with operator() overloaded. That is, you set your parameters in the constructor, and then pass the instance itself, which can be called as a function, where it is necessary.
PS See my examples in the last comment...
This function definitely has a friend, which is called similarly, but accepts void*.
Exactly the same void* is received by the function that registers this callback, after which this void*, in fact, gets into the callback.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question