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

Pointing to a function that is a class member - GLFW setKeycallback(指向属于类成员的函数 - GLFW setKeycallback)
本文介绍了指向属于类成员的函数 - GLFW setKeycallback的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在编写一个 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).

这篇关于指向属于类成员的函数 - GLFW setKeycallback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)