GLFW setUserPointer / getUserPointer发送/访问类崩溃

时间:2016-05-02 19:29:16

标签: c++ opengl glfw

当我尝试使用glfwSetUserPointer / glfwGetUserPointer发送和访问类时,我打印随机值并且应用程序崩溃。我可以成功地以相同的方式发送结构,但我想发送一个类,所以我不必管理多个事情。我假设static_cast不起作用,如果是的话,什么是替换?回调包括Test类声明。

class Test
{
public:
    Test() { ; }

    string aString;
};

GLFWwindow *GLFWwin;
GLFWwin = glfwCreateWindow(1920, 1080, "myProj", 0, 0);

auto myTest = new Test();
myTest->aString = "str";
cout << "myTest->aString = " << myTest->aString << endl; //prints "str"

glfwSetWindowUserPointer(GLFWwin, &myTest);
glfwSetCursorPosCallback(GLFWwin, myCursorPosCallback);

do
{

    glClear(GL_COLOR_BUFFER_BIT);
    glfwSwapBuffers(GLFWwin);
    glfwPollEvents();
}

while (glfwWindowShouldClose(GLFWwin) == 0);


void myCursorPosCallback(GLFWwindow *GLFWwin, double xPos, double yPos)
{
    auto *myTest = static_cast<Test*>(glfwGetWindowUserPointer(GLFWwin));
    cout << "myTest->aString = " << myTest->aString << endl; //prints random vals then crash
}

1 个答案:

答案 0 :(得分:2)

将您创建的Test()对象的地址作为窗口用户指针传递:

auto myTest = new Test();
glfwSetWindowUserPointer(GLFWwin, &myTest);

myTest的类型为Test*,您在此处获取指针的地址,这意味着&myTest的类型为Test**myTest指针本身是一个局部变量,一旦超出范围就会变为无效。在实践中,这意味着您将指向堆栈上的某个随机位置的指针传递给glfwSetWindowUserPointer,当您稍后将其检索并取消引用时,您将获得未定义的行为。

将ponter传递给你的对象:

glfwSetWindowUserPointer(GLFWwin, myTest);