2

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?

genpfault
  • 51,148
  • 11
  • 85
  • 139
Gen0me
  • 115
  • 8
  • Also see https://stackoverflow.com/questions/2298242/callback-functions-in-c?rq=1 for a broad overview of callbacks in C++. – Max Langhof Sep 16 '19 at 12:26
  • 1
    @MaxLanghof No this is not duplicate. The question is related to GLFW and for GLFW there is a special solution. – Rabbid76 Sep 16 '19 at 12:29
  • 1
    @Rabbid76 Yes, the duplicate was not good. But these should be correct: https://stackoverflow.com/questions/28283724/use-a-member-function-as-callback or https://stackoverflow.com/questions/7676971/pointing-to-a-function-that-is-a-class-member-glfw-setkeycallback (also see https://www.glfw.org/faq.html#216---how-do-i-use-c-methods-as-callbacks). – Max Langhof Sep 16 '19 at 12:34

2 Answers2

1

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); 
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

void Console_Input(GLFWwindow* window, unsigned int letter_i) should be a global function, it cannot be a member function of a class

anwsering your question: no there is no way to put this in a class.