指向属于类成员的函数 - GLFW setKeycallback

2021-12-13 00:00:00 function class pointers c++ glfw

我正在编写一个 GLFW 应用程序,其中我将函数调用包装到一个简单的类中.我在设置键回调时遇到问题.我的班级定义为:

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

class GAME 
{
private:
    bool running;
public:
    GAME();
    int execute();
    void events(int, int);
    int loop();
    int render();
};

执行函数是:

int GAME::execute() 
    {
        glfwOpenWindow(640, 320, 8, 8, 8, 8, 0, 0, GLFW_WINDOW);
        glfwSetWindowTitle("Viraj");
        glfwSetKeyCallback(events);
        running = true;
        while(glfwGetWindowParam(GLFW_OPENED))
        {
            glfwPollEvents();
            loop();
            render();
        }
        return 0;
    }

在 Visual Studio 2010 上编译以下代码会出现错误:

Compiling the following code on Visual Studio 2010 gives the error:

error C3867:'GAME::events':函数调用缺少参数列表;使用&GAME::events"创建一个指向成员的指针

使用 &GAME::events 给出:

error C2664: 'glfwSetKeyCallback' : 无法将参数 1 从 'void (__thiscall GAME::* )(int,int)' 转换为 'GLFWkeyfun' 1>没有上下文可以进行这种转换

推荐答案

有一个 C++ 语法用于指向类成员方法,但您不能将它们传递给 C 风格的 API.C 理解函数调用和每一个非静态对象方法,以你的 events 为例,在 C 语言中看起来是这样的:void events(void* this, int, int); 意味着除了标准参数之外的每个方法也会得到一个 this 指针,静默传递.

There is a C++ syntax for pointing to class member methods but you cannot pass them to a C style API. C understands function calls and every non-static object method, taking your events as an example, looks like this thinking in C terms: void events(void* this, int, int); meaning that every method apart from the standard arguments also gets a this pointer silently passed.

为了让你的 events C 兼容,让它static void events(int, int);.这样它将遵循 C 调用语义 - 它不需要传递 this 指针.您还必须以某种其他方式将您的对象以某种方式传递给此回调(如果您在回调中需要此对象的数据).

To make your events C compatible make it static void events(int, int);. This way it will follow the C calling semantics - it will not require a this pointer getting passed. You have to also somehow pass your object to this callback in some other manner (if you need this object's data in the callback).

相关文章