OpenGL glShaderSource抛出异常

时间:2016-12-28 15:04:16

标签: c++ opengl exception

此代码抛出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);
}

1 个答案:

答案 0 :(得分:2)

你的电话错了:

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

并且从size_t转换为指针类型的类型应该在您编写时引发了一些红色标记。

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

由于您已经使用了0终止的C字符串,因此您只需使用NULL作为length参数即可。或者,如果您绝对想要使用它,则只需将指针传递给GLint:

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