简体   繁体   中英

SDL2 + OpenGL access violation

This works fine:

int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window* window = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 
SCR_WIDTH, SCR_HEIGHT, SDL_WINDOW_OPENGL);

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_GLContext mainContext = SDL_GL_CreateContext(window);

    gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress);

    SDL_Event event;
    int running = 1;

    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

    ...

    return 0;
}

But if I wrap the initialization into a class I get an access violation when I call glCreateShader even though I'm not getting any error messages when initializing SDL and OpenGL:

int main(int argc, char** argv)
{
    WindowManager wm;
    if (!wm.Construct())
        return 0;

    SDL_Event event;
    int running = 1;

    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); //<---- access violation here

    ...        

    return 0;
}

Here is my WindowManager class with the relevant functions:

class WindowManager
{
public:
    WindowManager() = default;
    
    bool Construct()
    {
        if (SDL_Init(SDL_INIT_VIDEO) < 0);
            return false;

        mWindow = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, 
        height, SDL_WINDOW_OPENGL);

        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

        mContext = SDL_GL_CreateContext(mWindow);

        if (!mWindow)
        {
             spdlog::error("WindowManager could not be created!");

             return false;
        }

        if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
        {
            spdlog::error("Failed to initialize GLAD!");

            return false;
        }

        return true;
    }

    SDL_Window* mWindow;
    SDL_GLContext mContext;
};

If anyone could some shine some light on what the issue could be I would greatly appreciate it!

Since I was compiling WindowManager into a dll and using it in a separate project, I essentially made two programs.

Program A had an initialized OpenGL context but Program B that was using WindowManager did not.

So I had to write a function to expose the glProcAddress to Program B in order to make raw OpenGL calls such as glCreateShader().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM