其他分享
首页 > 其他分享> > c – 尝试在方法中包装glGenVertexArrays时调用分段错误

c – 尝试在方法中包装glGenVertexArrays时调用分段错误

作者:互联网

我正在尝试在Mac OS上使用SDL 2.0.3和C的“现代”OpenGL(3),如果我直接调用OpenGL函数它就可以工作,但是当我尝试将它包装在类中时它不起作用.更具体地说,我想将Vertex数组对象存储为类成员,并在类方法中调用glGenVertexArrays,但这会导致段错误.

直接调用的最小工作示例(没有任何用处,但不会崩溃):

#include <cstdlib>
#include <SDL.h>
#include <OpenGL/gl3.h>

int main()
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window *sdlWindow = SDL_CreateWindow(
        "OpenGL Works",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        640,
        480,
        SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI
    );
    SDL_GLContext sdlGLContext = SDL_GL_CreateContext(sdlWindow);

    unsigned int vertexArrayObject;

    // This works
    glGenVertexArrays(1, &vertexArrayObject);

    // Wait some seconds before closing the window
    SDL_Delay(3000);

    SDL_GL_DeleteContext(sdlGLContext);
    SDL_DestroyWindow(sdlWindow);

    return EXIT_SUCCESS;
}

不使用简单类(分段错误):

#include <cstdlib>
#include <memory>
#include <SDL.h>
#include <OpenGL/gl3.h>

class Graphics
{
    public:
        void createVAO();

    private:
        unsigned int vertexArrayObject;
};

void Graphics::createVAO()
{
    glGenVertexArrays(1, &this->vertexArrayObject);
}

int main()
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

    SDL_Window *sdlWindow = SDL_CreateWindow(
        "OpenGL Shit",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        640,
        480,
        SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI
    );
    SDL_GLContext sdlGLContext = SDL_GL_CreateContext(sdlWindow);

    std::unique_ptr<Graphics> g;

    g->createVAO();

    // Wait some seconds before closing the window
    SDL_Delay(3000);

    SDL_GL_DeleteContext(sdlGLContext);
    SDL_DestroyWindow(sdlWindow);

    return EXIT_SUCCESS;
}

glGenBuffers也是如此.我想知道它是否仅仅是由于我缺乏c技能而导致的“简单”C问题,或者它是否是与OpenGL和/或SDL相关的更严重的问题.我在Stack Overflow上发现了很多关于类似症状的问题,但大多数都是由缺少的选项引起的glewExperimental = GL_TRUE;对于我没有使用的GLUT或GLEW,或者我有一个缺少的OpenGL上下文,因为我能够在屏幕上绘图:

> Segmentation fault at glGenVertexArrays( 1, &vao );
> Program Crash on glGenVertexArrays call
> Implementing VBO in OpenGL, the window stay black
> OpenGL Segfaults on glGenVertexArrays

我希望有人能解释为什么这会崩溃,因为我不能:(

我使用的是Mac OS 10.9.3,编译器是Apple LLVM版本5.1(clang-503.0.40)(基于LLVM 3.4svn),这是编译器调用:c -o OpenGLTest main.cpp -I /usr/local/include / SDL2 -lSDL2 -framework OpenGL

解决方法:

std::unique_ptr<Graphics> g;
g->createVAO();

你在哪里填充g的东西?

现在看起来你正在取消引用一个NULL指针.

试试这个:

std::unique_ptr<Graphics> g( new Graphics );

标签:sdl-2,opengl-3,c,macos,opengl
来源: https://codeday.me/bug/20190830/1770030.html