Jump to content
  • Advertisement
Sign in to follow this  
X Abstract X

Loading GLSL Shader from File C++

This topic is 2988 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.
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());
}



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>"

Share this post


Link to post
Share on other sites
Advertisement
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;
}




Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!