从文件中读取GLSL着色器 [英] read GLSL shaders from file

查看:117
本文介绍了从文件中读取GLSL着色器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从看起来像这样的文件中读取顶点和片段着色器

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

推荐答案

这里的问题是,字符串 content 在函数的末尾超出范围,从而删除了整个内容.然后返回的是指向已释放的内存地址的指针.

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

我在这里看到两种方法来防止这种情况:要么返回字符串本身,而不是返回指向其内存的指针,要么在堆上创建GLchar *数组,然后在其中复制内容.

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.

这篇关于从文件中读取GLSL着色器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆