[英]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. 这里的问题是,字符串
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. 我在这里看到两种方法来防止这种情况:要么返回字符串本身,而不是返回指向其内存的指针,要么在堆上创建GLchar *数组,然后在其中复制内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.