<分区>
我正在使用 GLFW3(窗口库)制作应用程序,我的操作系统是 Windows 8.1。
我的错误:我在我的主线程中创建了一个指针,而窗口的线程得到一个 access violation。当它尝试使用它时。
在我的应用程序中,我试图制作一个输入处理程序类,它从窗口接收事件并将它们发送到订阅该事件的所有对象。
为此,我让所有想要监听的对象继承 InputListener
:
class InputListener{
public:
virtual void onKeyDown(int key) = 0;
};
要订阅一个事件,一个对象必须使用一个伪全局(传递给构造类的引用)包装器变量,它包含我的InputHandler
:
// My global wrapper
#include "InputHandler.h"
class Centrum{
public:
InputHandler inputHandler;
public:
Centrum(){}
};
输入处理器
class InputHandler{
private:
unsigned numEvents;
InputListener* key_down; // Only trying to test on one subscriber for now.
public:
InputHandler();
void registerKeyDown(InputListener* listener, int key);
void key_event(int key, int action); // Is indirectly called by glfw window (same thread though)
};
// Implementation
InputHandler::InputHandler(){
numEvents = 0;
}
void InputHandler::registerKeyDown(InputListener* listener, int key){
// This is called from my main thread
key_down = listener;
key_down->onKeyDown(key); // Properly calls function on my Camera class which inherits InputListener
numEvents++;
printf("yes %u\n", numEvents);
}
void InputHandler::key_event(int key, int action){
// This is called by the window's thread (glfw automatically makes this thread)
printf("failure %u\n", numEvents); // Properly prints out numEvents
key_down->onKeyDown(key); // Runtime error here, access violation
}
订阅输入的例子:
Camera::Camera(Centrum& g_centrum){
this->g_centrum = g_centrum;
[...]
g_centrum.inputHandler.registerKeyDown(this, GLFW_KEY_W);
}