PDA

View Full Version : What's wrong with my file to char function? (glShaderSource)



yj1214
08-14-2015, 05:18 PM
glShaderSource();



This is my file to char conversion function...




char **convToChar(const char *file_path){
FILE *file;
file = fopen(file_path, "rb");
unsigned int length;
char *buffer;

if(file){
fseek(file, 0, SEEK_END);
length = ftell(file);
buffer = malloc(length + 1);
fseek(file, 0, SEEK_SET);
//buffer = calloc(length, sizeof(char));
fread(buffer, length, 1, file);
fclose(file);

buffer[length] = '\0';
printf("%s", buffer);
}

char **dp_buffer = &buffer;

return dp_buffer;
}



I can just use this function to send my shader code to 'glShaderSource' function.



const GLchar *vertexShaderCode = *convToChar("shader/vertexshader.myextension");
glShaderSource(vertexShaderID, 1, &vertexShaderCode, 0);


Same code for the fragment shader code...

Funny thing is sometimes the debugger says 'Attached vertex shader is not compiled' but sometimes it says 'Attached fragment shader is not compiled'.


This is my shader code but I don't think there is any problem with it.



#version 430


in layout(location = 0) vec2 position;

void main(){
gl_Position = vec4(position, 0.0, 1.0);
}



So my question is what's wrong with my code? or is there recommended text to char function? could you share it please? thank you.

Alfonse Reinheart
08-14-2015, 05:44 PM
char **dp_buffer = &buffer;

This statement retrieves a pointer to a stack variable. Once you leave this function, that pointer becomes invalid. Yet you return that pointer to the calling function. And thus, the caller has a pointer to an invalid variable.

The correct answer is to return `buffer` itself. That will be a pointer to memory you allocated, so it will still exist afterwards. Also, your function should just return a `char*`, not a `char**`.

yj1214
08-14-2015, 06:03 PM
char *convToChar(char *file_path){
FILE *file;
file = fopen(file_path, "rb");
unsigned int length;
char *buffer;

if(file){
fseek(file, 0, SEEK_END);
length = ftell(file);
buffer = malloc(length + 1);
fseek(file, 0, SEEK_SET);
//buffer = calloc(length, sizeof(char));
fread(buffer, length, 1, file);
fclose(file);

buffer[length] = '\0';
}

return buffer;
}


This is my new version but it still doesn't work...



GLchar *vertexShaderCode = convToChar("shader/vertexshader.myextension");
glShaderSource(vertexShaderID, 1, (const GLchar **)&vertexShaderCode, 0);



I honestly have no idea what I did wrong...

yj1214
08-15-2015, 12:09 AM
Oh...I forgot to compile my shaders...


Sorry guys!!!!!!!!

it won't happen again!