使用SDL库的可执行文件的奇怪行为

Strange behaviour with executable using SDL library

本文关键字:可执行文件 SDL 使用      更新时间:2023-10-16

我使用SDL构建了一个空间入侵者克隆,并使用MSVC11编译。该代码加载4个独立的PNG文件和一个TTF字体,用于渲染。当给定一个绝对文件路径时,该程序运行得非常好,例如"C:\/spaceinvider.png".

我尝试将其更改为相对文件路径,即"./res/spaceinvider.png

然后在发布模式下对程序进行编译,并将其放置在自己的文件夹中。

目录结构:

gamegame.exe
game(all the required SDL dlls)
gameresimage1.png (and the other 3 images)
gameresfont.ttf

最奇怪的事情发生在你试图运行游戏的时候。第一次尝试运行时,程序控制台加载,SDL窗口打开,然后崩溃到桌面。(我已经确保main()中没有过早的返回代码)。然而,在随后的所有时间里,程序都会加载并工作,尽管其中一个精灵不会显示在屏幕上。控制台中出现的唯一错误与两个PNG文件的sRGB配置文件不正确有关。

如果整个文件夹被移到不同的位置,程序第一次不会再次加载,但随后会加载

所以我的问题是

1) 为什么程序不是第一次加载,而是随后加载?2) 当文件都相同(在photoshop中创建)并且加载它们的代码相同时,为什么只有一个sprite无法显示?

(很抱歉没有在这里包含任何代码,因为我不觉得这是一个编码问题-很高兴根据要求粘贴特定的代码段)

谢谢!K

编辑:

图像加载代码(loadTexture函数从这里抄袭:

SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
{
SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
log_CheckSDLPointer(std::cout, texture, "LoadTexture");
return texture;
}
int Gamestate::initialiseSprites(SDL_Renderer *Renderer)
{
enemytexture = loadTexture("./res/invader.png", Renderer);
if (enemytexture == nullptr) {return 1;}
playertexture = loadTexture("./res/player.png", Renderer);
if (playertexture == nullptr) {return 1;}
missiletexture = loadTexture("./res/bullet.png", Renderer);
if (missiletexture == nullptr) {return 1;}
background = loadTexture("./res/background.png", Renderer);
if (background == nullptr) {return 1;}
return 0;
}

这个函数主要被调用:

if (Active_Gamestate.initialiseSprites(mainRenderer) != 0)
{
return 1;  //quit game if sprites could not be initialised
}

感谢您的帮助。我想我已经弄清楚了发生了什么。如果图像加载代码改为以下代码:

char executablePath[FILENAME_MAX];
std::stringstream invaderpathstream;
invaderpathstream << executablePath << "/res/invader.png";
std::string invaderpath = invaderpathstream.str();
enemytexture = loadTexture(invaderpath, Renderer);
if (enemytexture == nullptr) 
{return 1;}

问题消失了。也许问题出在相对路径上(至少在我的系统上),也许在程序第一次运行后,操作系统会以某种方式找到所需的文件,这就是为什么它在后续运行中不会出现问题?

K