Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I give a global callback function a local instance?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

glfwSetKeyCallback(window, key_callback);

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

>Solution :

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading