2012-09-08 13 views
13

Debería tener la última versión de Glew y Glut, así que ese no debería ser el problema. Todo debe estar vinculado, y estoy usando MS visual studio 2010. Mi programa se compila, pero cuando llego a glCreateShader (GL_FRAGMENT_SHADER) muestra un error: "0xC0000005: infracción de acceso".glCreateShader se cuelga

mi programa:

#include <GL\glew.h> 
#include <GL\glut.h> 
#include <stdio.h> 
#include <stdlib.h> 

GLuint program; 

static char* readShaderSource(const char * shaderFile) 
{ 
    FILE* fp = fopen(shaderFile, "r"); 
    char* buf; 
    long size; 

    if (fp == NULL) return NULL; 
    fseek(fp, 0L, SEEK_END);//go to end 
    size = ftell(fp);  //get size 
    fseek(fp, 0L, SEEK_SET);//go to begining 

    buf = (char*) malloc((size +1) * sizeof(char)); 
    fread(buf, 1, size, fp); 
    buf[size] = NULL; 
    fclose(fp); 
    return buf; 
} 

static void initShader(const GLchar * fsFile) 
{ 
    GLint status; 
    GLchar * fSource; 
    GLuint fShader; 
    GLuint fShader2; 

    //read file 
    fSource = readShaderSource(fsFile); 
    if (fSource == NULL) 
    { 
     printf("Fail to load file"); 
     exit(EXIT_FAILURE); 
    } 

    //Create program and shader object 
    fShader2 = glCreateShader(GL_VERTEX_SHADER); 
    fShader = glCreateShader(GL_FRAGMENT_SHADER); 
    program = glCreateProgram(); 

    //Attach shaders to program 
    glAttachShader(program, fShader); 

    //read shaders 
    glShaderSource(fShader, 1, (const GLchar**) &fSource, NULL); 

    //compile fragment shader 
    glCompileShader(fShader); 

    //error check 
    glGetShaderiv(fShader, GL_COMPILE_STATUS, &status); 
    if (status == GL_FALSE) 
    { 
     printf("Failed to compile the fragment shader."); 
     exit(EXIT_FAILURE); 
    } 

    //link and error check 
    glLinkProgram(program); 
    glGetProgramiv(program, GL_LINK_STATUS, &status); 
    if (status == GL_FALSE) 
    { 
     printf("program error"); 
     exit(EXIT_FAILURE); 
    } 

    //use program object 
    glUseProgram(program); 

    //set up uniform parameter 
    //skipped for now 
} 

int main(int argc, char ** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); 
    glutInitWindowSize(500,500); 
    glutCreateWindow("Matrix Fractal"); 
    glClearColor(1.0, 1.0, 1.0, 1.0); 
    gluOrtho2D(0.0,0.0,(GLfloat) 500, (GLfloat) 500); 

    glutDisplayFunc(draw); 
    glutReshapeFunc(reshape); 

    initShader("fsFractal.glsl"); 

    glutMainLoop(); 
} 

Respuesta

37

Usted tiene que inicializar GLEW antes de poder usarlo:

GLenum err = glewInit();

+0

Gracias Ben. Funcionó. Sin embargo, utilicé otra variante que estoy publicando como respuesta a continuación para mayor claridad. – sinner

2

Hay otra situación en la que esto puede ocurrir y las condiciones están lejos de ser evidente. Si decide utilizar GLFW Y Glew en su aplicación, también puede terminar en glCreateShader() ACCESS_VIOLATION, si escribió:

Si cambia esta línea para

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); 

la ACCESS_VIOLATION debido al puntero de función NULL glCreateShader() se ha ido.

No me preguntes, cómo las dos bibliotecas glew y glfw interfieren entre sí ... ¡alerta de vudú!

+2

He resuelto ese problema llamando a glewInit() después de glfwMakeContextCurrent(). – jimvonmoon

+0

Además de la sugerencia de @jimvonmoon, la ventana a la que pertenece el sombreador debe estar actualizada en ese momento de la creación del sombreador. Este fue mi error. – scones

+0

Gracias, me salvaste de 10 días de depuración – Matth

0

Aquí está mi variante que es un seguimiento de la respuesta de @ BenRujil anterior.

glewExperimental = GL_TRUE; 
    if(glewInit() != GLEW_OK) 
     throw std::runtime_error("glewInit failed"); 
0

Si está utilizando GLFW y GLEW/GLXW, consiguiendo una violación de acceso para la dirección 0 que puede suceder si usted está tratando de inicializar GLEW/GLXW antes crear un contexto OpenGL válida con GLFW:

if (!glfwInit()) { 
    std::cerr << "GL initialization failed" << std::endl; 
    return 1; 
} 
// Setup the openGL profile you need - we're going with a 4.3 core profile 
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); 
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); 
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 
// Context creation happens in the line below 
GLFWwindow *window = glfwCreateWindow(800, 600, "text", NULL, NULL); 
if (!window) { 
    std::cerr << "Window or GL initialization failed"; 
    glfwTerminate(); 
    return 1; 
} 
glfwMakeContextCurrent(window); 
if (glxwInit()) { // Now it's a good time to initialize Xtension wranglers 
    std::cerr << "Failed to initialize GLXW" << std::endl; 
    return 1; 
} 

Calling glxwInit() antes de la creación contexto recogerá cualquier contexto predeterminado se establece y que puede desencadenar la violación de acceso (puede ser que necesite para ser recogidos en tiempo de ejecución).