Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLFW callback inside class [duplicate]

This works: (main):

glfwSetCharCallback(window, Console_Input);

(global):

void Console_Input(GLFWwindow* window, unsigned int letter_i){
}

If I try to put it inside class: (main):

Input_text Text_Input(&Text_Input_bar, &GLOBALS);
glfwSetCharCallback(window, Text_Input.Console_Input);

(global):

class Input_text{
...
void Console_Input(GLFWwindow* window, unsigned int letter_i){

}
void Update(){
    if(active == 1){
        MBar->Re_set_bar_width(str);
        MBar->update_bar();
    }
}
};

It doesnt work. I get error: cannot convert 'Input_text::Console_Input' from type 'void (Input_text::)(GLFWwindow*, unsigned int)' to type 'GLFWcharfun {aka void ()(GLFWwindow, unsigned int)}' I dont want to write functionality inside callback function. I need self-managing class. Is there a way to set glfwSetCharCallback to the function inside a class?

like image 481
Gen0me Avatar asked Dec 03 '25 16:12

Gen0me


1 Answers

The callback has to be a function (or static method), but you can associate a user pointer to a GLFWindow. See glfwSetWindowUserPointer.

The pointer can be retrieved at an time form the GLFWWindow object by glfwGetWindowUserPointer

Associate a pointer to Text_Input, to the window:

Input_text Text_Input(&Text_Input_bar, &GLOBALS);

glfwSetWindowUserPointer(window, &Text_Input);
glfwSetCharCallback(window, Console_Input);

Get the pointer form the window and Cast the pointer of type void* to Input_text * (Sadly you have to do the cast).

void Console_Input(GLFWwindow* window, unsigned int letter_i)
{
   Input_text *ptr= (Input_text *)glfwGetWindowUserPointer(window); 
   ptr->Console_Input(window, i); 
}
like image 82
Rabbid76 Avatar answered Dec 06 '25 07:12

Rabbid76