调用glGenBuffers时openGL崩溃

Posted

技术标签:

【中文标题】调用glGenBuffers时openGL崩溃【英文标题】:openGL crashing when calling glGenBuffers 【发布时间】:2016-08-25 02:35:17 【问题描述】:

我正在通过http://learnopengl.com/ 学习 OpenGL,但是当我尝试在教程的“hello triangle”部分中绑定缓冲区时,我崩溃了。我以前有 C++ 编码经验,但我不知道哪里出了问题。

我的代码:

#include <iostream>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GL/glfw3.h>
#include <GL/gl.h>

using namespace std;



const GLuint WIDTH = 800, HEIGHT = 600;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
int initializeWindow(GLFWwindow* window);
int main() 

    GLFWwindow* window;

    cout << "Creating Triangles" << endl;
    GLfloat triangles[] = 
            -0.5f, -0.5f, 0.0f,
             0.5f, -0.5f, 0.0f,
             0.5f,  0.5f, 0.0f
    ;

    cout << "Initialising GLFW" << endl;
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    cout << "Initialising Window..." << endl;
    window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", NULL, NULL);

    cout << "Setting Callback Functions..." << endl;
    glfwSetKeyCallback(window, key_callback);

    cout << "Binding Buffers" << endl;
    GLuint VBO;
    glGenBuffers(1, &VBO); // <--- Crashing here
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangles), triangles, GL_STATIC_DRAW);

    if (initializeWindow(window) == -1) 
        return -1;
    

    while(!glfwWindowShouldClose(window)) 
        glfwPollEvents();

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glfwSwapBuffers(window);
    

    cout << "Terminating..." << endl;
    glfwTerminate();
    return 0;


int initializeWindow(GLFWwindow* window) 

        if (window == NULL) 
            cout << "Failed to create GLFW window... exiting" << endl;
            glfwTerminate();
            return -1;
        

        glfwMakeContextCurrent(window);

        glewExperimental = GL_TRUE;
        if(glewInit() != GLEW_OK) 
            cout << "Failed to initialize GLEW... exiting" << endl;
            return -1;
        

        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);

        return 0;


void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) 
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) 
        glfwSetWindowShouldClose(window, GL_TRUE);
    

我只是遇到了一般的“无响应”崩溃,控制台中没有错误。任何帮助将不胜感激,谢谢。

【问题讨论】:

【参考方案1】:

您需要在创建窗口之后和调用 gl 函数之前调用initializeWindow。这对于激活当前窗口并初始化 glew 是必要的(这些操作在 initializewindow 内部完成)

【讨论】:

啊,我完全忘记了我在 if 语句中初始化了窗口。谢谢!

以上是关于调用glGenBuffers时openGL崩溃的主要内容,如果未能解决你的问题,请参考以下文章

glGenBuffers - 释放内存?

glDeleteBuffers() 在析构函数调用期间崩溃

OpenGL:随机调用 OpenGL 函数时崩溃

调用OpenGL函数时程序崩溃

OPENGL的buffer_offset

opengl渲染4k数据提高效率