从回调函数访问实例

Access instance from callback function

本文关键字:实例 访问 函数 回调      更新时间:2023-10-16

如何访问 GLFW3 输入回调函数中的类实例,例如这个。

我希望我的实例在特定事件发生时执行某些操作。每个实例可能会对特定事件执行不同的操作。

具体来说,我的类有一个 std::map<int、std::function><void()>>,其中键映射到函数。

编辑:我尝试了以下内容,但这给了我一个错误,它与glfwSetKeyCallback函数调用不匹配。

glfwSetKeyCallback(window, [this](GLFWwindow * window, int key, int scancode, int action, int mods){
    addCommand(m_events.at(key));
});

取自这里。

你需要这样的东西:

glfwSetWindowUserPointer(window, this);
glfwSetKeyCallback(window, [](GLFWwindow * window, int key, int scancode, int action, int mods){
    Window * win = static_cast<Window *>(glfwGetWindowUserPointer(window));
    win->addCommand(win->m_events.at(key));
});