C++中通过his指针指示一个对象的方法

Indicate an object's method through his pointer in C++

我目前正在学习 C++ 中的 OpenGL。

我正在尝试通过设置 glfwSetKeyCallback(this->window, ctrl->key_callback); 来读取键盘输入,其中 this->window 是我的 GLFWwindow* windowctrl->key_callback 是我的自定义对象 Controller.

我在使用 MSVC 时遇到编译器错误:

non-standard syntax; use '&' to create a pointer to member

如何通过 Controller* ctrl 指针指示 key_callback 方法?

出现错误的地方:

void Class1::set_callback(Controller* ctrl)
{
    glfwSetKeyCallback(this->window, ctrl->key_callback);
}

Controller.h

#include "Class1.h"
#include "GLFW/glfw3.h"

class Controller
{
    public:
        Controller(Class1* c);
        ~Controller();
        void key_callback(GLFWwindow* glwindow, int key, int scancode, int action, int mods);

    private:
        Window* window;
};

我正在 main.cpp

给 set_callback 打电话
#include "Class1.h"
#include "Controller.h"

int main()
{
    Class1* my_class = new Class1();
    Controller* controller = new Controller(my_class);
    my_class->set_callback(controller);
    return 0;
}

如果我没有正确表述 question/title,请告诉我,我对这种语法很困惑

你不能。非静态成员函数有一个 this 参数。 void key_callback(GLFWwindow* glwindow, int key, int scancode, int action, int mods)的签名其实是void key_callback(Controller*this, GLFWwindow* glwindow, int key, int scancode, int action, int mods)。所以根本不满足glfwSetKeyCallback.

的要求

我建议你使用 thunk 函数(独立函数或静态成员函数):

void key_callback_thunk(GLFWwindow* glwindow, int key, int scancode, int action, int mods) {
    auto self = static_cast<Controller*>(glfwGetWindowUserPointer(glwindow));
    self->key_callback(glwindow, key, scancode, action, mods);
}

void Class1::set_callback(Controller* ctrl)
{
    glfwSetWindowUserPointer(this->window, ctrl);
    glfwSetKeyCallback(this->window, key_callback_thunk);
}

请注意,glfwSetWindowUserPointer 只能为给定的 window 存储一个指针。您再次调用它,该值将被覆盖。

回调不能有成员函数,glfwSetKeyCallback接受一个指向自由函数的指针。它的签名是

GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);

其中 GLFWkeyfun

typedef void(* GLFWkeyfun) (GLFWwindow *, int, int, int, int);