glfw 如何在 mainloop 中销毁 window

glfw how to destroy window in mainloop

我正在尝试使用 glfw 开发一个程序,其中 window 在主循环中关闭。但是,我得到了这个奇怪的 运行 时间错误:

X Error of failed request:  GLXBadDrawable
  Major opcode of failed request:  152 (GLX)
  Minor opcode of failed request:  11 (X_GLXSwapBuffers)
  Serial number of failed request:  158
  Current serial number in output stream:  158

这是我正在尝试的代码 运行

#include <GL/glfw3.h>

int main()
{
    GLFWwindow* window;

    if(!glfwInit())
        return -1;

    window = glfwCreateWindow(400, 400, "window", nullptr, nullptr);

    if(!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    while(!glfwWindowShouldClose(window))
    {
        glfwDestroyWindow(window);

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

有什么方法可以从主循环内部破坏 window 吗?

是的,你可以在主循环中调用glfwDestroyWindow。这是我的做法。

#include <GLFW/glfw3.h>

int main()
{
    GLFWwindow* window;
    
    if(!glfwInit())
        return -1;

    window = glfwCreateWindow(400, 400, "My Window", NULL, NULL);

    if(!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    while(!glfwWindowShouldClose(window))
    {
        if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
        {
            glfwDestroyWindow(window);
            break;
        }

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

按Q键销毁window。试试 运行 这段代码看看它是否有效。我 运行 这段代码和进程只是返回 0 而没有打印任何错误消息。我不明白为什么它不适合你。