glfwSetWindowUserPointer
Attaches one pointer of your own to the window, so callbacks can reach your objects without globals.
Signature
void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer);
How it works
GLFW callbacks are plain C functions: they receive the window and the event, nothing else. If the key callback must move a camera, how does it find the camera? The quick answer is a global variable; the clean one is the user pointer.
Store a pointer to your app object once, then read it back inside any callback with glfwGetWindowUserPointer. GLFW never looks at it or frees it.
Parameters
The window to attach the pointer to.
Any pointer, usually this or the address of your app struct. Starts as NULL.
Tips & pitfalls
The object must live as long as the window, or callbacks will read a dangling pointer.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GLFW_NOT_INITIALIZED
- Called before glfwInit or after glfwTerminate.
Example
1struct App { Camera camera; };
2App app;
3glfwSetWindowUserPointer(window, &app);
4glfwSetScrollCallback(window, [](GLFWwindow* w, double, double dy) {
5 auto* app = static_cast<App*>(glfwGetWindowUserPointer(w));
6 app->camera.zoom(dy);
7});