简体   繁体   中英

read GLSL shaders from file

i'm trying to read vertex and fragment shader from files that look like this

#version 330 core
in vec3 ourColor;

out vec4 color;

void main()
{
    color = vec4(ourColor, 1.0f);
}

but when i'm compiling shader i get the error like 'bad syntax'. 在此处输入图片说明

code that read shader code from file

const GLchar* readFromFile(const GLchar* pathToFile)
{
    std::string content;
    std::ifstream fileStream(pathToFile, std::ios::in);

    if(!fileStream.is_open()) {
        std::cerr << "Could not read file " << pathToFile << ". File does not exist." << std::endl;
        return "";
    }

    std::string line = "";
    while(!fileStream.eof()) {
        std::getline(fileStream, line);
        content.append(line + "\n");
    }

    fileStream.close();
    std::cout << "'" << content << "'" << std::endl;
    return content.c_str();
}

The problem here is, that the string content gets out of scope at the end of the function, which deletes the whole content. What you return is then a pointer to an already freed memory address.

const GLchar* readFromFile(const GLchar* pathToFile)
{
    std::string content; //function local variable
    ....
    return content.c_str();
} //content's memory is freed here

I see two methods here to prevent this: Either return the string itself instead of a pointer to its memory, or create a GLchar* array on the heap and copy the content there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM