c++ - 使用鼠标单击与鼠标光标移动的回调时出现 OpenGL 未处理的异常

标签 c++ opengl

在提问之前,我将公开部分代码以更好地解释它。

我使用 OpenGL 3.3GLFW 来处理鼠标事件。

我有我的 OpenGL :

class OpenGL
{
public:
    OpenGL();
    ~OpenGL();

private:
    //(...)
    void registerCallBacks();

    static void mouseMove(GLFWwindow* window, double xpos, double ypos);
    static void mouseClick(GLFWwindow* window, int button, int action, int mods);

    GLFWwindow*     m_window;
};

我在其中注册鼠标事件的回调

void OpenGL::registerCallBacks()
{
    glfwSetWindowUserPointer(m_window, this);

    glfwSetCursorPosCallback(m_window, mouseMove);
    glfwSetMouseButtonCallback(m_window, mouseClick);
}

从回调中调用的方法是这些(在头文件中是静态):

void OpenGL::mouseMove(GLFWwindow* window, double xpos, double ypos)
{
    void* userPointer = glfwGetWindowUserPointer(window);
    Mouse* mousePointer = static_cast<Mouse*>(userPointer);
    mousePointer->move(xpos,ypos); //EXECUTE MOVE AND CRASH on glfwSwapBuffers()
}

void OpenGL::mouseClick(GLFWwindow* window, int button, int action, int mods)
{
    void* userPointer = glfwGetWindowUserPointer(window);  
    Mouse* mousePointer = static_cast<Mouse*>(userPointer);
    mousePointer->click(button,action); //EXECUTE CLICK AND IT'S OK!!
}

如您所见,我有一个处理鼠标事件的 Mouse 类:

class Mouse
{
public:
    Mouse();

    ~Mouse();

    void click(const int button, const int action); //called from the mouseClick() in the OpenGL class
    void move(const double x, const double y); //called from the mouseMove()  in the OpenGL class

private:
    double m_x;
    double m_y;
};

其中 move 方法只是这样:

void Mouse::move(const double x, const double y)
{
    m_x = x;
    m_y = y;
}

click方法只是这样:

void Mouse::click(const int button, const int action)
{
    printf("button:%d, action:%d\n",button, action);
}

我的问题是:

我的 openGL 主循环在循环末尾有:glfwSwapBuffers(m_window);,如果我使用 Mouse::move() 方法如上所示。 如果我注释掉move()方法的内容,就完全没有问题了。

我什至可以正确地从 click() 中看到 printf's

我认为 move() 和 click() 方法之间没有区别...

这里发生了什么?为什么仅当我使用 move() 时,glfwSwapBuffers(m_window); 才会出现崩溃?为什么不在 click() 中,因为两者的构造方式相同,使用各自的回调

注意:我确实需要使用 move() 方法来“保存”鼠标坐标,以便稍后在 click() 方法上使用。

错误:

Unhandled exception at 0x001F2F14 in TheGame.exe: 0xC0000005: Access violation reading location 0x4072822C.

最佳答案

您将 GLFW 的用户指针设置为 OpenGL 类对象的 this,但在回调中,您将其强制转换为 Mouse 类。这些类之间也没有继承关系,因此通过该指针访问任何成员变量或方法都会导致未定义的行为,这在您的情况下表现为崩溃。

关于c++ - 使用鼠标单击与鼠标光标移动的回调时出现 OpenGL 未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33506914/

相关文章:

c++ - glm 旋转和平移

c++ - Boost fusion 使用 lambda fold 参数包

javascript - 使用 v8 读取二进制文件的函数

c++ - 如何使用 system() 函数在 C++ 中存储 cmd 内存 [C++]

c++ - 我是否必须在函数实现中重复内联关键字

c++ - 一个接一个地加载对象时,OpenGL indexbuffer 不工作

windows - 为什么 OpenGL 和 CUDA 上下文内存贪婪?

c++ - glAttribLocation 返回 -1,即使顶点着色器正在积极使用它

OpenGL : How can I put the skybox in the infinity

c++ - 使用函数指针作为模板方法的默认参数时出错