OpenGL使用鼠标点击与鼠标光标移动的回调时出现未处理的异常
OpenGL Unhandled exception when using callbacks from mouse clicks vs mouse cursor moves
在提问之前,我将公开部分代码以更好地解释它。
我使用OpenGL 3.3
和GLFW
来处理鼠标上的事件。
我有我的OpenGL class
:
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;
};
其中,我为鼠标事件注册callbacks
。
void OpenGL::registerCallBacks()
{
glfwSetWindowUserPointer(m_window, this);
glfwSetCursorPosCallback(m_window, mouseMove);
glfwSetMouseButtonCallback(m_window, mouseClick);
}
从回调调用的方法如下(头文件上的static
):
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!!
}
正如你所看到的,我有一个处理鼠标事件的鼠标类:
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:%dn",button, action);
}
我的问题是:
我的openGL主循环在循环的末尾有一个:glfwSwapBuffers(m_window);
,如果我使用如上所示的Mouse::move()
方法,它将在这一行崩溃。如果我对move()
方法的内容进行评论,则完全没有问题。
我甚至可以从click()
中正确地看到printf's
。
我看不出move()和click()方法之间有什么区别。。。
这里发生了什么?为什么只有当我使用move()
时,glfwSwapBuffers(m_window);
才会出现崩溃?为什么不在click()
中,因为两者都是以相同的方式构建的,使用各自的callbacks
?
注意:我确实需要使用move()
方法来"保存"鼠标坐标,以便以后在click()
方法上使用。
错误:
Unhandled exception at 0x001F2F14 in TheGame.exe: 0xC0000005: Access violation reading location 0x4072822C.
您将GLFW的用户指针设置为OpenGL
类对象的this
,但在回调中,您将其强制转换为Mouse
类。这些类之间也没有继承关系,因此通过该指针访问任何成员变量或方法都会导致未定义的行为,在您的情况下,这种行为表现为崩溃。
相关文章:
- 架构决策:返回std::future还是提供回调
- 正在为Xtensa simcall函数编写回调函数
- 如何在C++中使用非静态成员函数作为回调函数
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 用于在回调中调用解析器的设计模式
- 如何使用C++对象的成员函数作为 C 样式回调?
- Java从C++回调到C++回调
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 从不同的 cpp 调用回调函数会导致bad_function_call
- 我想制作设置鼠标回调函数,以便在仍然按下鼠标左键时连续传递坐标
- 鼠标离开 GLFW窗口后触发 GLFW 鼠标回调?
- C++ OpenCV 鼠标回调继承类
- 哪些消息可以传递给低级鼠标挂钩回调函数
- 使用鼠标回调修改类中的 Mat 属性
- OpenGL使用鼠标点击与鼠标光标移动的回调时出现未处理的异常
- c++中使用push_back的一个鼠标回调函数
- opencv窗口在鼠标回调时未刷新
- 鼠标回调函数 OpenCV
- 鼠标回调函数中void*转换为int*** (opencvc++)