使用 glfw3 glew 和 opengl 在 Visual Studio 社区中获取访问冲突异常

64h*_*ans 2 c++ opengl glew glfw

我遇到这个问题已经有一段时间了,我无法为我的爱找到解决方案。

我想渲染一个简单的三角形。但是我在编译程序时一直在visual studio中得到这个输出。

注意> 我不相信这不是链接问题,而是其他问题。我无数次检查我的链接器,一切都在那里!

链接:https : //pastebin.com/xeTDd0Qu

主要的

static const GLfloat g_vertex_buffer_data[] = {
    100.0f, 100.0f, 0.0f,
    150.0f, 100.0f, 0.0f,
    100.0f, 150.0f, 0.0f,
};



GLFWwindow* window;
window = initWindow(640, 480, "Title");


GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);


GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

while (!glfwWindowShouldClose(window)) {

    glViewport(0, 0, 640, 480);
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glFlush();

    glfwSwapBuffers(window);
    glfwPollEvents();
}

glfwTerminate();

return 0;
Run Code Online (Sandbox Code Playgroud)

初始化窗口()

GLFWwindow* initWindow(int a_width, int a_height, const char* title) {
glewExperimental = GL_TRUE;
int err = glewInit();
if (!err) {
    exit(-1);
}

if (!glfwInit()) {
    printf("glfwInit() failed!");
    return nullptr;
}

GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL);

if (!window) {
    glfwTerminate();
    return nullptr;
}

return window;
Run Code Online (Sandbox Code Playgroud)

}

谢谢!

编辑:我得到的异常消息:ConvexHullVisualiser.exe 中的 0x00000000 处抛出异常:0xC0000005:访问冲突执行位置 0x00000000。

BDL*_*BDL 5

你得到的错误告诉你你正在尝试执行一个指向 NULL 的函数指针。大多数 OpenGL 函数是(在 Windows 上)函数指针并在运行时加载。总的来说,这意味着您正在尝试执行尚未加载的 OpenGL 函数。

最有可能的是,发生这种情况是因为只有在存在有效的 OpenGL 上下文时才能成功初始化 GLEW。由于上下文是由glfwCreateWindow,glewInit必须在此行之后调用。

您还缺少glfwMakeContextCurrent将 OpenGL 上下文绑定到活动线程的调用。

if (!glfwInit()) {
    printf("glfwInit() failed!");
    return nullptr;
}

GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL);

if (!window) {
    glfwTerminate();
    return nullptr;
}

glfwMakeContextCurrent(window);

glewExperimental = GL_TRUE;
int err = glewInit();
if (!err) {
    exit(-1);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这glewInit不会返回一个 int 而是一个GLenum. 正确的错误检查应该看起来像这样:

GLenum err = glewInit();
if (GLEW_OK != err)
{
  /* Problem: glewInit failed, something is seriously wrong. */
  fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  ...
}
Run Code Online (Sandbox Code Playgroud)

来源:GLEW 文档