GLFW window callbacks inside classes

Hello everyone! I’m currently working on a GLFW + OpenGL project with C++. I’ve set up some Tests and a window with ImGui to switch between these tests. Each test is like a main application. In one of the tests, I want to set some window callbacks, so I created those callbacks as methods inside the TestFPS class. But when I’m calling glfwSet…Callback(), I get an error because of incompatible types. It is caused because of the callback functions, which have a type of void(test::TestFPS::) instead of void (). How can I fix this while having the callback functions inside my class? (I want to use some class attributes inside the callback functions). Thank you!

Edit: this is the exact error.

error: cannot convert 'test::TestFPS::framebuffer_size_callback' from type 'void (test::TestFPS::)(GLFWwindow*, int, int)' to type 'GLFWframebuffersizefun' {aka 'void (*)(GLFWwindow*, int, int)'}

Hi @Gert2198 welcome to the GLFW forum,

You can’t use member functions as callbacks unless they are static, as the signature is different for member functions (they require the object pointer to dereference).

You can use window user pointers to set the member pointer so you can then call your member function from a free function.

For example see What is a possible use of glfwGetWindowUserPointer? - #2 by tombsar

Thank you for the reply, @dougbinks! The post you sent was very useful to set my mind. But I don’t exactly know how to use that information in my code.

Should I create a class that stores all the variables I want to change in the callback? Or should I set the window user pointer to the memory address of the TestFPS object I have?

I’m going to post my GitHub repository with the project, so you can understand what I try to do. Gert2198/PruebaOpenGL (github.com). The class is in src/tests/TestFPS, and the callback I’m trying to set is the mouse_callback.

I would appreciate some advice based on my code, but it doesn’t matter if it’s more general and for other applications.

I would set the window user pointer to the memory address of the TestFPS object you have, then in the free function callback call the TestFPS member function using that pointer.

I’ve done what you said, and it works!! Thank you so much :slight_smile: