【发布时间】:2018-06-30 20:19:19
【问题描述】:
我正在使用 SDL 和 SDL_Image 加载图像以用作 opengl 的纹理。
我正在尝试加载多个图像排列成水平行(在同一图像中)的精灵表
void load_spritesheet(std::string key, const char *file_name, int width, int height, int nframes) {
GLuint *texture = new GLuint[nframes];
auto src = IMG_Load(file_name);
auto dstrect = new SDL_Rect{0, 0, width, height};
for(int i = 0; i < nframes; i++) {
auto dst = SDL_CreateRGBSurface(0, width, height, 1, src->format->Rmask, src->format->Gmask, src->format->Bmask, src->format->Amask);
auto rect = new SDL_Rect { i*width, 0, width, height };
SDL_BlitSurface(src, rect, dst, dstrect);
load_gltex(dst, &texture[i]);
SDL_FreeSurface(dst);
}
SPRITESHEET_CACHE[key] = texture;
SDL_FreeSurface(src);
}
我单步执行了代码,在循环的第一次迭代中它运行良好。在第二次迭代中,我在调用SDL_BlitSurface 时遇到了段错误,传入的指针都不是NULL,并且没有任何表面被锁定或类似的东西。我确信我的矩形在每个表面的范围内。
以下是 gdb 在段错误之前的一些值:
print i
1
print *src
{flags = 0, format = 0x847100, w = 416, h = 32, pitch = 1664, pixels = 0x87c5f0, userdata = 0x0, locked = 0, lock_data = 0x0, clip_rect = {x = 0, y = 0, w = 416, h = 32}, map = 0x8537b0, refcount = 1}
print *dst
{flags = 0, format = 0x855ec0, w = 32, h = 32, pitch = 4, pixels = 0x84d1f0, userdata = 0x0, locked = 0, lock_data = 0x0, clip_rect = {x = 0, y = 0, w = 32, h = 32}, map = 0x6bdfc0, refcount = 1}
print *rect
{x = 32, y = 0, w = 32, h = 32}
print *dstrect
{x = 0, y = 0, w = 32, h = 32}
在同一个表面上调用SDL_BlitSurface 两次或类似的东西是否不安全?谢谢。
【问题讨论】:
-
您应该检查所有这些函数返回的值,尤其是
SDL_BlitSurface。此外,您的程序会泄漏内存,因为您从不删除使用new分配的内容。SDL_Rect可以在堆栈上分配。为SDL_CreateRGBSurface调用提供 1 作为深度也很奇怪,通常应该是 32。 -
谢谢!是的,我意识到我可以更改那些在堆栈上分配的
new SDL_Rect调用。我检查了SDL_BlitSurface的返回值,它在第一次调用时返回零(根据 SDL 文档,这意味着它是成功的,如果出现错误,它将是非零值)