为什么需要检查 GLAD 或 GLEW 是否正确初始化?

ssj*_*ack 0 c++ opengl glew visual-studio

我正在使用 GLFW + GLAD 或 GLEW ( ) 设置 opengl #include glad/glad.h #include <GL/glew.h>。在该函数之后,glfwMakeContextCurrent(window);我需要检查 GLAD 或 GLEW 是否已正确初始化,否则我将在 Visual Studio 2019 中遇到异常错误

#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <iostream>
using namespace std;

int main(void) {

GLFWwindow* window;

/* 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);

/* Check if GLEW is ok after valid context */
/*if (glewInit() != GLEW_OK) {
    cout << "Failed to initialize GLEW" << endl;
}*/
/* or Check if GLAD is ok after valid context */
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
    cout << "Failed to initialize GLAD" << endl;
    return -1;
}

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Render here */
    glClear(GL_COLOR_BUFFER_BIT);
    
    ...
}

glfwTerminate();
return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里我用的是GLAD。我真的不明白为什么我必须检查这个。提前致谢。

der*_*ass 5

这里我用的是GLAD。我真的不明白为什么我必须检查这个

if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
Run Code Online (Sandbox Code Playgroud)

这里的关键点不是检查,而是gladLoadGLLoader实际初始化 GLAD 并加载所有 GL 函数指针的调用。因此,您在这里所做的就是初始化GLAD,然后检查该函数的返回值,该值会告诉您 GLAD 是否能够正确初始化。

所以如果你不想“检查”,正确的代码就是

gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
Run Code Online (Sandbox Code Playgroud)

省略检查当然不是一个好主意,因为这意味着您可能会尝试调用可能未加载的 GL 函数指针,这很可能会使您的应用程序崩溃 - 当您甚至不尝试初始化它时也会看到相同的错误,就像你已经做的那样。