在C ++中将文本(字符串转换为const char *)

时间:2018-06-08 22:45:52

标签: c++ opengl glsl

修改

我已经阅读了所有推荐的帖子,我已尝试过这些解决方案,但没有人帮助过。

简而言之,问题在于

的第三个论点
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);

此代码工作:

 const char *vertexShaderSource = "#version 120 \n"
                             "attribute vec3 pos;\n"
                             "attribute vec2 texCoord;\n"
                             "varying vec2 texCoord0;\n"
                             "uniform mat4 transform;\n"
                             "void main()\n"
                             "{\n"
                             "   gl_Position = transform * vec4(pos, 1.0);\n"
                             "   texCoord0 = texCoord;\n"
                            "}\0";

但是我希望在代码工作之后从文件中读取它

std::string s= "vertex";
std::ifstream file(s.c_str());
std::stringstream buffer;

buffer << file.rdbuf();
std::string str = buffer.str();
std::cout << str; 

正在输出:

 #version 120
 attribute vec3 pos;
 attribute vec2 texCoord;
 varying vec2 texCoord0;
 uniform mat4 transform;

 void main()
 {
     gl_Position = transform * vec4(pos, 1.0);
     texCoord0 = texCoord;
 }

从你的回答中我知道我不能简单地用这样的代码转换字符串:

 const char *vertexShaderSource = str.c_str();

并将其传递给:

 glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);

所以我使用了以下代码来阻止它停止存在:

 char * writable = new char[str.size() + 1];
 std::copy(str.begin(), str.end(), writable);
 writable[str.size()] = '\0';

传递glShaderSource(vertexShader, 1, &writable, NULL);也不起作用。我还能做什么?

END OF EDIT

我正在尝试将代码重写为一个函数,该函数将文件名作为参数,并返回glShaderSource接受的格式,并且某处我犯了愚蠢的错误,这就是函数:

processFile:

const char* processFile(const std::string fileName){

    std::ifstream file;
    file.open(fileName.c_str(), std::ios::in);

    std::string output;
    std::string line;

  if(file.is_open())
  {
      while(file.good())
      {
        getline(file, line);
        output.append(line + "\n");
      }
  }
  else
  {
    std::cerr << "Unable to load shader"  << std::endl;
  }


     const char * shaderCode = output.c_str();
     return shaderCode;

   //I've tried also:
   //  char* result = new char[output.length()+1];
   //  strcpy(result,output.c_str());
   //  return result;
 }

函数调用:

const char *vertexShaderSource = processFile("./vertex"); //I am writing on linux

请注意有效的代码:

const char *vertexShaderSource = "#version 120\n"
                                 "attribute vec3 pos;\n"
                                 "void main()\n"
                                 "{\n"
                                 "   gl_Position = vec4(pos, 1.0f);\n"
                                 "}\0";



vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);

错误讯息:

0:1(1): error: syntax error, unexpected $end
0:1(1): error: syntax error, unexpected $undefined

我做错了什么?

0 个答案:

没有答案