Pointing to a function that is a class member - glfw setKeycallback

前端 未结 7 1245
遇见更好的自我
遇见更好的自我 2020-12-02 11:27

I\'m writing a glfw app, in which I\'ve wrapped the function callse into a simple class. Im having trouble setting the key callback. My class is defined as:

         


        
7条回答
  •  星月不相逢
    2020-12-02 12:15

    I had the same problem and after reading this thread I came up with a similar solution. I think it is a bit cleaner this way. It's based on static function but it is nested inside the class where we set all things.

    Header looks like this:

    class Application
        {
        public:
            ...
        private:
            ...
            void MousePositionCallback(GLFWwindow* window, double positionX, double positionY);
            void KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
            ...
            class GLFWCallbackWrapper
            {
            public:
                GLFWCallbackWrapper() = delete;
                GLFWCallbackWrapper(const GLFWCallbackWrapper&) = delete;
                GLFWCallbackWrapper(GLFWCallbackWrapper&&) = delete;
                ~GLFWCallbackWrapper() = delete;
    
                static void MousePositionCallback(GLFWwindow* window, double positionX, double positionY);
                static void KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
                static void SetApplication(Application *application);
            private:
                static Application* s_application;
            };
        };
    

    And the source code:

    void Application::GLFWCallbackWrapper::MousePositionCallback(GLFWwindow* window, double positionX, double positionY)
    {
        s_application->MousePositionCallback(window, positionX, positionY);
    }
    
    void Application::GLFWCallbackWrapper::KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
    {
        s_application->KeyboardCallback(window, key, scancode, action, mods);
    }
    
    void Application::GLFWCallbackWrapper::SetApplication(Application* application)
    {
        GLFWCallbackWrapper::s_application = application;
    }
    
    Application* Application::GLFWCallbackWrapper::s_application = nullptr;
    
    void Application::MousePositionCallback(GLFWwindow* window, double positionX, double positionY)
    {
        ...
    }
    
    void Application::KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
    {
        ...
    }
    
    void Application::SetCallbackFunctions()
    {
        GLFWCallbackWrapper::SetApplication(this);
        glfwSetCursorPosCallback(m_window, GLFWCallbackWrapper::MousePositionCallback);
        glfwSetKeyCallback(m_window, GLFWCallbackWrapper::KeyboardCallback);
    }
    

提交回复
热议问题