我有一个读取文件并将其内容作为a返回的方法std::string
.我使用return std::string
来编译OpenGL程序.在某些情况下,由于一个或两个着色器部分(读取文件内容),链接失败(编译的顶点着色器已损坏.)NULL
.
如果我一步一步调试我的代码一切都很好.
如果我打印文件内容,链接似乎失败的次数较少.
为什么它表现不同,哪里是我的错?
将cout
在年底始终打印正确的文件内容:
std::string read_file(const char* filePath) { std::string content; std::ifstream stream(filePath, std::ios::in); if (stream.is_open()) { std::string line = ""; while(getline(stream, line)) { content += "\n" + line; } } std::cout << "read_file " << content << "end read_file" << std::endl; // always prints the correct content return content; // makes a copy, don't like that, unless RVO?.. }
该fragmentSource
和或vertextSource
有时是空的:
GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER); const char* fragmentSource = tools::read_file(_fragmentShaderPath).c_str(); std::cout << "vertext shader source: " << std::endl << fragmentSource; // empty sometimes glShaderSource(fragmentShaderID, 1, &fragmentSource, NULL); glCompileShader(fragmentShaderID); CheckCompilation(fragmentShaderID); const char* vertexSource = tools::read_file(_vertexShaderPath).c_str(); std::cout << "vertext shader source: " << std::endl << vertexSource; // empty sometimes glShaderSource(vertexShaderID, 1, &vertexSource, NULL); glCompileShader(vertexShaderID); CheckCompilation(vertexShaderID); GLuint programId = glCreateProgram(); glAttachShader(programId, fragmentShaderID); glAttachShader(programId, vertexShaderID); glLinkProgram(programId); GLint result = GL_FALSE; GLint infoLogLength; glGetProgramiv(programId, GL_LINK_STATUS, &result); glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { // this fails sometimes, corresponding to either vertexSource or fragmentSource being empty std::vectorinfoLog(infoLogLength + 1); glGetProgramInfoLog(programId, infoLogLength, NULL, &infoLog[0]); std::cout << &infoLog[0] << std::endl; }
ybungalobill.. 10
更换
const char* fragmentSource = tools::read_file(_fragmentShaderPath).c_str();
同
std::string fragmentSourceStr = tools::read_file(_fragmentShaderPath); const char* fragmentSource = fragmentSourceStr.c_str();
同样的事情vertexSource
.
问题是您返回的字符串是临时的,因此在fragmentSource
使用指向其数据的指针进行初始化后会被销毁,这fragmentSource
表明存储已被破坏.
更换
const char* fragmentSource = tools::read_file(_fragmentShaderPath).c_str();
同
std::string fragmentSourceStr = tools::read_file(_fragmentShaderPath); const char* fragmentSource = fragmentSourceStr.c_str();
同样的事情vertexSource
.
问题是您返回的字符串是临时的,因此在fragmentSource
使用指向其数据的指针进行初始化后会被销毁,这fragmentSource
表明存储已被破坏.