GLEW glGenBuffers segfault



我正在尝试将OpenGL与SDL一起使用以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <SDL2/SDL.h>
#include <GL/glew.h>
GLuint* SetupCubeBuffers(void)
{
    GLuint *buffers = NULL;
    GLfloat vertexBuffer[48] = {
        1.0, 0.0, 0.0, -1.0, 1.0, -1.0,
        1.0, 0.0, 1.0, -1.0, -1.0, -1.0,
        1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
        0.0, 0.0, 1.0, -1.0, -1.0, 1.0,
        0.0, 1.0, 0.0, 1.0, 1.0, 1.0,
        0.0, 1.0, 1.0, 1.0, -1.0, 1.0,
        1.0, 1.0, 0.0, 1.0, 1.0, -1.0,
        1.0, 1.0, 1.0, 1.0, -1.0, -1.0
    };
    GLuint indexBuffer[36] = {
        0, 1, 2, 2, 1, 3,
        4, 5, 6, 6, 5, 7,
        3, 1, 5, 5, 1, 7,
        0, 2, 6, 6, 2, 4,
        6, 7, 0, 0, 7, 1,
        2, 3, 4, 4, 3, 5
    };
    glGenBuffers(2, buffers);
    glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexBuffer), vertexBuffer, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexBuffer), indexBuffer, GL_STATIC_DRAW);
    return buffers;
}
void DrawBuffers(GLuint* buffers)
{
    glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
    glVertexPointer(3, GL_FLOAT, 6 * sizeof(float), (float*)NULL + 3);
    glColorPointer(3, GL_FLOAT, 6 * sizeof(float), 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
}
int main(int argc, char** argv)
{
    int wndHold = 1;
    SDL_Event e;
    SDL_Window *screen;
    SDL_GLContext con;
    GLenum glewStatus;
    GLuint* buffers;
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        fprintf(stderr, "Error: %snn", SDL_GetError());
    }
    screen = SDL_CreateWindow("test",
                              SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED,
                              640, 480,
                              SDL_WINDOW_OPENGL);
    con = SDL_GL_CreateContext(screen);
    glewStatus = glewInit();
    if (glewStatus != GLEW_OK)
    {
        printf("Error: %snn", glewGetErrorString(glewStatus));
    }
    SDL_GL_SetSwapInterval(1);
    glClearColor(0.0, 0.0, 0.0, 1.0);
    buffers = SetupCubeBuffers();
    while (wndHold)
    {
        glClear(GL_COLOR_BUFFER_BIT);
        DrawBuffers(buffers);
        SDL_GL_SwapWindow(screen);
        SDL_WaitEvent(&e);
        if (e.type == SDL_QUIT)
        {
            wndHold = 0;
        }
    }
    SDL_GL_DeleteContext(con);
    SDL_DestroyWindow(screen);
    SDL_Quit();
    return 0;
}

,但是当我执行程序时,我会得到" test.exe停止工作"错误。在调试模式下,我可以看到当我调用GlgenBuffers时有一个segfault。但是,glewinit()在初始化gl上下文后立即调用,所以我看不到这里有什么问题?

我在Windows 8上,我正在使用SDL 2.0

您的glgenbuffers函数正在尝试写入null,因此segfault。您需要先初始化数组,然后再尝试任何写入:

GLuint *buffers = new GLuint[2];

相关内容

  • 没有找到相关文章

最新更新