glfwSetCharCallback不接受我的函数签名,该如何解决?
问题根源
你传入的callbackFun是类的非静态成员函数,这类函数会隐式携带一个this指针作为第一个参数,导致它的实际签名和GLFW要求的GLFWcharfun(即void(*)(GLFWwindow*, unsigned int))不匹配,因此编译器提示签名错误。另外代码里的uint建议替换成标准的unsigned int,避免因类型别名差异引发额外问题。
解决方案
方案一:静态成员函数 + 窗口用户指针
将回调改为静态成员函数,同时把当前类对象的指针存入窗口的用户数据区,在回调中取出后访问非静态成员:
- 先修改类声明,把
callbackFun标记为static:
class MultiLauncher { public: int run(); static void callbackFun(GLFWwindow* window, unsigned int codepoint); private: KeyEvents keyEventsInstance; // 假设这是你的成员变量 // 其他成员... };
- 修改
run()和回调的实现:
int MultiLauncher::run() { std::cout << "Begin..." << std::endl; GLFWwindow* window = initApp(); // 将当前对象指针存入窗口的用户数据 glfwSetWindowUserPointer(window, this); // 设置静态回调 glfwSetCharCallback(window, callbackFun); figure triangle; while (!glfwWindowShouldClose(window) && keepRunningGame) { glClear(GL_COLOR_BUFFER_BIT); triangle.buildFigure(); triangle.drawFigure(); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } void MultiLauncher::callbackFun(GLFWwindow* window, unsigned int codepoint) { // 取出存储的类对象指针 MultiLauncher* launcher = static_cast<MultiLauncher*>(glfwGetWindowUserPointer(window)); std::cout << codepoint << std::endl; // 通过对象指针访问非静态成员 launcher->keyEventsInstance.processKey(codepoint); }
方案二:无捕获Lambda(C++11及以上)
利用无捕获Lambda作为回调,同样结合窗口用户指针传递类对象:
int MultiLauncher::run() { std::cout << "Begin..." << std::endl; GLFWwindow* window = initApp(); glfwSetWindowUserPointer(window, this); // 直接用无捕获Lambda作为回调 glfwSetCharCallback(window, [](GLFWwindow* window, unsigned int codepoint) { MultiLauncher* launcher = static_cast<MultiLauncher*>(glfwGetWindowUserPointer(window)); std::cout << codepoint << std::endl; launcher->keyEventsInstance.processKey(codepoint); }); // 后续游戏循环代码不变... }
内容的提问来源于stack exchange,提问作者LondonNight
相关产品推荐
相关产品推荐

