首页 > 解决方案 > 类内的 GLFW 回调

问题描述

这有效:(主要):

glfwSetCharCallback(window, Console_Input);

(全球的):

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

如果我尝试把它放在课堂上:(主要):

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

(全球的):

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();
    }
}
};

它不起作用。我收到错误:无法将 'Input_text::Console_Input' 从类型 'void (Input_text::)(GLFWwindow*, unsigned int)' 类型转换为 'GLFWcharfun {aka void ( )(GLFWwindow , unsigned int)}' 我不想在回调函数中编写功能。我需要自我管理课程。有没有办法将 glfwSetCharCallback 设置为类中的函数?

标签: c++classopenglglfw

解决方案


回调必须是函数(或静态方法),但您可以将用户指针关联到GLFWindow. 见glfwSetWindowUserPointer

可以通过以下方式一次从GLFWWindow对象中检索指针glfwGetWindowUserPointer

将指向 ,的指针关联Text_Inputwindow:

Input_text Text_Input(&Text_Input_bar, &GLOBALS);

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

从 the 中获取指针window并将类型的指针转​​换void*Input_text *(遗憾的是,您必须进行转换)。

void Console_Input(GLFWwindow* window, unsigned int letter_i)
{
   Input_text *ptr= (Input_text *)glfwGetWindowUserPointer(window); 
   ptr->Console_Input(window, i); 
}

推荐阅读