OpenGL GlshaderSource抛出了例外

OpenGL glShaderSource throws an exception

本文关键字:GlshaderSource OpenGL      更新时间:2023-10-16

此代码抛出nvoglv32.dll异常。我认为GlshaderSource某些服务器有错误,但我找不到它

ifstream ifs("vertexShader.txt");
string vertexShadersSource((istreambuf_iterator<char>(ifs)),
    (std::istreambuf_iterator<char>()));
ifs.close();
ifs.open("fragmentShader.txt");
string fragmentShadersSource((istreambuf_iterator<char>(ifs)),
    (std::istreambuf_iterator<char>()));
cout << fragmentShadersSource.c_str() << endl;
cout << vertexShadersSource.c_str() << endl;
GLuint shaderProgram;
GLuint fragmentShader, vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
const char *data = vertexShadersSource.c_str();
glShaderSource(vertexShader, 1, &data, (GLint*)vertexShadersSource.size());
data = fragmentShadersSource.c_str();
glShaderSource(fragmentShader, 1, &data, (GLint*)fragmentShadersSource.size());

编辑:

尽管我认为着色器正确,但在这里您可以看到着色器代码vertexshader:

#version 150
// in_Position was bound to attribute index 0 and in_Color was bound to       attribute index 1
//in  vec2 in_Position;
//in  vec3 in_Color;
// We output the ex_Color variable to the next shader in the chain
out vec3 ex_Color;
void main(void) {
// Since we are using flat lines, our input only had two points: x and y.
// Set the Z coordinate to 0 and W coordinate to 1
//gl_Position = vec4(in_Position.x, in_Position.y, 0.0, 1.0);
// GLSL allows shorthand use of vectors too, the following is also valid:
// gl_Position = vec4(in_Position, 0.0, 1.0);
// We're simply passing the color through unmodified
ex_Color = vec3(1.0, 1.0, 0.0);
}

fragmentshader:

#version 150
// It was expressed that some drivers required this next line to function   properly
precision highp float;
in  vec3 ex_Color;
out vec4 gl_FragColor;
void main(void) {
// Pass through our original color with full opacity.
gl_FragColor = vec4(ex_Color,1.0);
}

您的电话是错误的:

glShaderSource(vertexShader, 1, &data, (GLint*)vertexShadersSource.size());

和从size_t到指针类型的类型在您编写时应该增加一些危险信号。

glshadersource()期望指针到字符串lenghts 的数组 - 每个单独的字符串一个元素。由于您只使用1个字符串,因此它将尝试访问lenght[0]。这意味着它将您的字符串大小视为地址,并且该地址很可能不属于您的流程。

由于您已经使用了0端的C-string,因此您只需将NULL用作length参数即可。或者,如果您绝对想使用它,则必须将指针传递给闪光:

GLint len=vertexShadersSource.size();
glShaderSource(..., 1, ..., &len);