c++ - 调用 glGetString 时出现访问冲突错误
问题描述
我正在使用 SDL2 + GLAD 在 C++ 中创建一个 OpenGL 应用程序。在我的主要功能中,我有以下代码:
#include <iostream>
#include <SDL.h>
#include <glad\glad.h>
int main(int argc, char *argv[]) {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cout << "SDL could not be initialized.";
return 1;
}
SDL_GL_LoadLibrary(nullptr);
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_Window *window = SDL_CreateWindow("Hello world", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 500, 500, SDL_WINDOW_OPENGL);
if (window == nullptr) {
std::cout << "SDL could not open window";
return 1;
}
const SDL_GLContext context = SDL_GL_CreateContext(window);
if (context == nullptr) {
std::cout << "SDL could not create context";
return 1;
}
printf("OpenGL loaded\n");
printf("Vendor: %s\n", glGetString(GL_VENDOR));
printf("Renderer: %s\n", glGetString(GL_RENDERER));
printf("Version OpenGL: %s\n", glGetString(GL_VERSION));
printf("Version GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
int w, h;
SDL_GetWindowSize(window, &w, &h);
glViewport(0, 0, w, h);
glClearColor(0.0f, 0.5f, 1.0f, 0.0f);
SDL_Event event;
bool quit = false;
while (!quit) {
SDL_GL_SwapWindow(window);
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
}
}
return 0;
}
但是,当我运行它时,我收到以下错误:
Exception thrown at 0x0000000000000000 in TestApp.exe: 0xC0000005: Access violation executing location 0x0000000000000000.
消息被打印出来,OpenGL loaded
Visual Sutio 显示错误被抛出就printf("Vendor:%s\n", glGetString(GL_VENDOR));
行了。
我已确保在解决方案的属性窗口中正确链接 SDL2 和 GLAD。什么可能导致此错误?
解决方案
Glad Loader-Generator has to be initialized by either gladLoadGL
or gladLoadGLLoader
, right after creating and making current the OpenGL context by SDL_GL_CreateContext
.
See also OpenGL Loading Library - glad
e.g.:
const SDL_GLContext context = SDL_GL_CreateContext(window);
if (context == nullptr) {
std::cout << "SDL could not create context";
return 1;
}
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
{
std::cout << "Failed to initialize OpenGL context" << std::endl;
return -1;
}
printf("OpenGL loaded\n");
printf("Vendor: %s\n", glGetString(GL_VENDOR));
printf("Renderer: %s\n", glGetString(GL_RENDERER));
printf("Version OpenGL: %s\n", glGetString(GL_VERSION));
printf("Version GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
推荐阅读
- node.js - Mongoose Schemme 未验证
- powershell - 当在PowerShell中调整窗口大小时,具有背景颜色的Write-Host会用背景颜色填充整行
- shell - 如何在Shell中获取另一个字符串中的字符串的行号
- python - 如何从 sys.stdin 读取单词并过滤以“iary”结尾的单词
- tableau-api - 如何在画面的并排条形图中添加单个统一趋势线
- python - 在 Python 中计算 p 值
- python - 如何在 Flask-Restx 中返回嵌套的 json 响应
- django - 使用可变数量的关键字优化 django 中搜索过滤器的函数代码 - 代码太多,我是初学者
- .net-core - 无法在 c# dotnetcore 中调用 JNI 导出的函数
- perl - Perl Net::SMTP 在 Fedora 上失败