Problem at using glfwSetCursorPosCallback

Generally speaking, using this method( ):

void mouse_callback(GLFWwindow * window, double xpos, double ypos);
glfwSetCursorPosCallback(window, mouse_callback);

Now I have a parent class and a subclass, and I want the subclass to bind:

    test::Test* currentTest = nullptr;
    test::TestMenu* testMenu = new test::TestMenu(currentTest);
    currentTest = testMenu;
    testMenu->RegisterTest<test::TestClearColor>("Clear Color");
    testMenu->RegisterTest<test::TestTexture2D>("TexTexture 2D");
    glfwSetCursorPosCallback(window, currentTest->mouse_callback);

This will report an error, and after inquiring with GPT, he said that the error lies in:

In this code, the glfwSetCursorPosCallback function is used to set the mouse position callback function. You want to bind the callback function to the member function of the currentTest object.

C++member functions have a hidden parameter, which is a pointer to the object (this pointer), which is automatically passed during function calls. Therefore, when you try to currentTest ->mouse_ When the callback is directly passed to the glfwSetCursorPosCallback function, it will cause a type mismatch error because currentTest ->mouse_ Callback is a member function, while glfwSetCursorPosCallback expects a regular non member function.

To solve this problem, you can use a static member function or a global function as a callback function, and call the corresponding member function through the currentTest object. An example is as follows:

Class Test{


Static void mouse_ Callback (GLFW window * window, double xpos, double ypos){

Test * currentTest=reinterpret_ Cast<Test *>(glfwGetWindowUserPointer (window));

CurrentTest ->OnMouseCallback (xpos, ypos);


Virtual void OnMouseCallback (double xpos, double ypos){

//Implementing specific mouse callback logic in subclasses



//Associate the currentTest object with the GLFW window before registering the callback function

GlfwSetWindowUserPointer (window, currentTest);

//Set the callback function as a static member function

GlfwSetCursorPosCallback (window, Test:: mouse_callback);

In the above example, a static member function ‘mouse’ is defined in the Test class_ Callback ', which takes the GLFW window and mouse position as parameters. Internally, obtain the currentTest object associated with the window through the glfwGetWindowUserPointer function and call its member function OnMouseCallback.

In this way, you can bind the callback function to the member function of the currentTest object to implement the corresponding mouse callback logic.

I want to know if using this writing method is reasonable, using static, using global functions, or using a regular non member function

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.