What is a possible use of glfwGetWindowUserPointer?

Welcome to the forum!

A UserData field is a fairly common paradigm in C APIs that lets the user access contextual data from within callbacks without needing to make everything global. In essence, it lets you associate an arbitrary piece of data relevant to your program with a glfw window.

If you are trying to use glfw in a program that follows object-oriented design, for example, you can use this pointer to store the address of the instance that is handling a particular window, and forward the callbacks (which have to be static functions, because of the way the API works) to the appropriate member functions. e.g.

/* Constructor for the MyWindowHandler class */
MyWindowHandler (GLFWwindow * window) {
    ....
    glfwSetWindowUserPointer(window, reinterpret_cast<void *>(this));
}

...

/* Key event callback wrapper function */
static void key_callback (GLFWwindow * window, int key, int scancode, int action, int mods) {
    MyWindowHandler * handler = reinterpret_cast<MyWindowHandler *>(glfwGetWindowUserPointer(window));
    if (handler)
        handler->keyEvent(key, scancode, action, mods);
}
1 Like