在Project0_opengl.exe中的0x00000000处引发的异常:0xC0000005:执行访问位置0x00000000的访问冲突

时间:2019-03-24 14:38:43

标签: c++ opengl

我正在编写正确的代码,但是编译器会引发错误。该错误表明该错误位于glGenBuffers上,但是我已经从官方网站复制了该错误。我的错误在哪里?

#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <stdio.h>

int main(void)
{
    GLFWwindow* window;
    glewExperimental = GL_TRUE;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    float pos[6] = {
        -0.5f, -0.5f,
         0.0f,  0.5f,
         0.5f, -0.5f
    };

    GLuint buf;
    glGenBuffers(1, &buf);
    glBindBuffer(GL_ARRAY_BUFFER, buf);
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), pos, GL_STATIC_DRAW);

    if (glewInit() != GLEW_OK)
        printf("Error\n");

    printf("%s", glGetString(GL_VERSION));

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

glewInit()必须在OpenGL上下文成为当前glfwMakeContextCurrent之后被调用。
但是必须在任何OpenGL指令之前调用它。另请参见Initializing GLEW

// [...]

/* Make the window's context current */
glfwMakeContextCurrent(window);

glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
    printf("Error\n");

float pos[6] = {
    -0.5f, -0.5f,
     0.0f,  0.5f,
     0.5f, -0.5f
};

GLuint buf;
glGenBuffers(1, &buf);
glBindBuffer(GL_ARRAY_BUFFER, buf);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), pos, GL_STATIC_DRAW);

// [...]

注意,诸如glGenBuffers之类的指令是函数指针。这些指针被初始化为NULLglewInit()将函数的地址分配给那些指针。
当您尝试在初始化之前调用函数时,这会导致:

  

访问冲突执行位置0x00000000

相关问题