Getting garbage chars when reading GLSL files

前端 未结 2 1313
野的像风
野的像风 2021-01-07 04:54

I run into the following problem.I load my shaders from files.The shader program ,when trying to compile, throws these errors for the vertex and fragment shaders:

V

相关标签:
2条回答
  • 2021-01-07 05:07

    It looks like all you have to do is allocate one more byte of memory in which you can place a null ('\0'):

    ...
    memblock = new char[1 + fSize]; 
    file.seekg (0, ios::beg);  
    file.read (memblock, size);  
    file.close();  
    memblock[size] = '\0';
    ...
    

    edit

    I changed my code to use fSize in the array rather than size, since it is a GLint, which is just a typedef over an integer. Also, I tried this fix on my machine, and it works as far as I can tell - no junk at the beginning, and none at the end.

    0 讨论(0)
  • 2021-01-07 05:17

    You're using C++, so I suggest you leverage that. Instead of reading into a self allocated char array I suggest you read into a std::string:

    #include <string>
    #include <fstream>
    
    std::string loadFileToString(char const * const fname)
    {
        std::ifstream ifile(fname);
        std::string filetext;
    
        while( ifile.good() ) {
            std::string line;
            std::getline(ifile, line);
            filetext.append(line + "\n");
        }
    
        return filetext;
    }
    

    That automatically takes care of all memory allocation and proper delimiting -- the keyword is RAII: Resource Allocation Is Initialization. Later on you can upload the shader source with something like

    void glcppShaderSource(GLuint shader, std::string const &shader_string)
    {
        GLchar const *shader_source = shader_string.c_str();
        GLint const shader_length = shader_string.size();
    
        glShaderSource(shader, 1, &shader_source, &shader_length);
    }
    
    void load_shader(GLuint shaderobject, char * const shadersourcefilename)
    {
        glcppShaderSource(shaderobject, loadFileToString(shadersourcefilename));
    }
    
    0 讨论(0)
提交回复
热议问题