我尝试使用SDL_ttf在OpenGL上渲染文本,但每次尝试从SDL_Surface获取像素时,都会引发以下错误:
Unhandled exception at 0x1000a590 in L2DF.exe:
0xC0000005: Access violation reading location 0x05b8f9e8.
我已经在发生错误的地方放置了断点,SDL_Surface指针看不到NULL,所有数据(如宽度和高度)都是正确的。
以下是代码:
void put_string(std::string text, bool filter=false)
{
SDL_Color col = {255, 255, 255};
SDL_Surface *txt = TTF_RenderText_Solid(sdl_font, text.c_str(), col);
if (txt == NULL) return;
GLuint tx;
glGenTextures(1, &tx);
glBindTexture(GL_TEXTURE_2D, tx);
if (filter)
{
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
// Here is where the error occurs...
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, txt->w, txt->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, txt->pixels);
// If I replace txt->pixels by NULL, the error is gone...
glBegin(GL_QUADS);
glTexCoord2d(0, 0); glVertex2d(0, 0);
glTexCoord2d(1, 0); glVertex2d(txt->w, 0);
glTexCoord2d(1, 1); glVertex2d(txt->w, txt->h);
glTexCoord2d(0, 1); glVertex2d(0, txt->h);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTextures(1, &tx);
SDL_FreeSurface(txt);
}