c++ - Project0_opengl.exe : 0xC0000005: Access violation executing location 0x00000000 中的 0x00000000 抛出异常

标签 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;
}

最佳答案

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() 将函数的地址分配给这些指针。
当您尝试在初始化之前调用该函数时,这会导致:

Access violation executing location 0x00000000

关于c++ - Project0_opengl.exe : 0xC0000005: Access violation executing location 0x00000000 中的 0x00000000 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324904/

相关文章:

c - OpenGL 的未知类型工件

c++ - 在 OpenGL 中使用 std::vector 作为顶点/元素列表

c++ - STL 映射的自定义内存分配器

c++ - 为什么这个指针为空

c++ - 声明对指针指向值的引用的开销

c++ - 在 Mac 10.6.3 上使用 gsl

c++ - 有没有办法在 C++ 中调用基类函数的所有子类?

c++ - OpenGL 在 3D 空间中渲染 2D

c++ - 如何巧妙地在 OpenGL 菜单系统中渲染文本?

arrays - OpenGL 顶点数组所需的版本