Home > Software design >  How can I give a global callback function a local instance?
How can I give a global callback function a local instance?

Time:10-17

In global namespace I have a GLFW callback function:

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
    {
        
    }
}

This function must recieve an object from local namespace of main function:

int main()
{
    ...
    Sphere lightSphere{ 0.8f, outerColor, centerColor };
    ...
}

And in main loop I have a GLFW callback function.

glfwSetKeyCallback(window, key_callback);

Is it possible to implement it without declaring an object in global namespace?

CodePudding user response:

Set the user pointer to window and retrieve it in the callback.

glfwSetWindowUserPointer(window, &lightSphere);
glfwSetKeyCallback(window, key_callback);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    Sphere* sphere = static_cast<Sphere*>(glfwGetWindowUserPointer(window));
}
  • Related