const char* Shader::loadShaderSource(const string& filename) {
std::ifstream file;
file.open(filename.c_str());
if (!file) {
return(0);
}
std::stringstream stream;
stream << file.rdbuf();
file.close();
return(stream.str().c_str());
}
Loading GLSL Shader from File C++
I've been trying to load a GLSL shader from file for a day now. I got the shader working by hard coding it into a char array but I can't seem to load it from the damn file. I've tried 3 different methods so far to load it but nope, no luck (Source included for the method I think is cleanest). Here's the code I have now and I would appreciate it if someone could tell me what I'm doing wrong. Thanks.
When I print out the result of the above function, there is no visible problems with the data.
The error I get when linking the shader is:
line 1: error C0000: syntax error, expected $undefined at token "<undefined>"
line 1: errorC0501: type name expected at token "<undefined>"
Objects die when they go out of scope, so does that stream when the function returns, copy the file string out before it dies.
bool Shader::loadShaderSource(const string& filename, string& out) { std::ifstream file; file.open(filename.c_str()); if (!file) { return false; } std::stringstream stream; stream << file.rdbuf(); file.close(); out = stream.str();return true;}
Yeah as mentioned above, the problem is with the lifetime of your string.
The c_str function returns a raw-pointer to the string's internal buffer, but when the string is destructed, this buffer is deallocated.
The c_str function returns a raw-pointer to the string's internal buffer, but when the string is destructed, this buffer is deallocated.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement