0

I'm currently learning OpenGL in C++.

I'm trying to read the keyboard inputs by setting glfwSetKeyCallback(this->window, ctrl->key_callback); Where this->windowis my GLFWwindow* window and ctrl->key_callback is a method of my custom object Controller.

I'm getting a compiler error with MSVC:

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

How can I indicate the key_callback method trough that Controller* ctrl pointer?

Where the error pops out:

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;
};

I'm calling set_callback in main.cpp

#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;
}

Please let me know if I didn't formulate my question/title right, I'm pretty confused with this syntax

GriffinBabe
  • 146
  • 1
  • 12

2 Answers2

2

You can't. Non static member function have a this parameter. The signature of void key_callback(GLFWwindow* glwindow, int key, int scancode, int action, int mods) is actually void key_callback(Controller*this, GLFWwindow* glwindow, int key, int scancode, int action, int mods). So it simply not meet the requirement of glfwSetKeyCallback.

I suggest you to use a thunk function (a standalone function or a static member function):

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);
}

Note that glfwSetWindowUserPointer can only store one pointer for a given window. You call it again, the value will be overrided.

W.H
  • 1,838
  • 10
  • 24
2

You can't have a member function for a callback, glfwSetKeyCallback takes a pointer to a free function. It's signature is

GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);

where GLFWkeyfun is

typedef void(* GLFWkeyfun) (GLFWwindow *, int, int, int, int);
jrok
  • 54,456
  • 9
  • 109
  • 141