我这里有一个 C++ 问题,我根本无法理解。
我有 2 个略有不同的函数。他们两个都应该做同样的事情。但只有一个能正常工作。
方法一:该方法的输入是'const string samplerName = "test"'
void setUniformSampler(Gluint program, const string samplerName, GLuint sampler) {
GLint uniformLocation = glGetUniformLocation(program, samplerName.c_str()); // returns -1
if(uniformLocation >= 0) {
glUniform1i(uniformLocation, sampler);
} else {
throw exception(...);
}
}
方法二:
void setUniformSampler(Gluint program, GLuint sampler) {
GLint uniformLocation = glGetUniformLocation(program, "test"); // returns 0
if(uniformLocation >= 0) {
glUniform1i(uniformLocation, sampler);
} else {
throw exception(...);
}
}
如您所见,glGetUniformLocation 返回 2 个不同的值。正确的返回值应该是“0”,而不是“-1”。所以我想知道,这两个调用之间到底有什么区别?
quote: "c_str() 生成一个以 null 结尾的字符序列(c 字符串),其内容与字符串对象相同,并将其作为指向字符数组的指针返回"。而这正是 glGetUniformLocation(...) 方法需要的第二个参数。那么,为什么只有上面的方法2成功了呢?是编译器问题吗?
我在 Win7 上使用 MS Visual Studio 2008。
我已经搜索这个错误将近 2 天了。我真的很想澄清这一点。这让我发疯...
谢谢 沃尔特
编辑:
这也行不通。
void setUniformSampler(Gluint program, const string samplerName, GLuint sampler) {
const GLchar* name = samplerName.c_str();
GLint uniformLocation = glGetUniformLocation(program, name); // still returns -1
if(uniformLocation >= 0) {
glUniform1i(uniformLocation, sampler);
} else {
throw exception(...);
}
}
最佳答案
你的参数是const,你不能在const对象上调用非const函数。也许这就是问题所在?该函数需要一个指向以 null 结尾的字符串的指针。确保这就是您所提供的内容。
关于C++,OpenGL : Weird problem with c-strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4395412/