2014-09-26 86 views
0

我在学习SDL 2.0,我一直在关注lazyfoo教程。问题在于这些教程将所有内容都保存在一个文件中。所以我试图在开始一个新的游戏项目时分割一些东西。我的问题是,当我从其余的分离我的纹理类时,它有时会崩溃程序,并不总是,但经常。SDL从文件加载图像

我有一个全局窗口和全局渲染器,我在我的课堂上使用。我在程序中的不同位置获得段错误,但始终处于以下功能之一中。

bool myTexture::loadFromFile(string path) { 
    printf("In loadFromFile\n"); 

    //Free preexisting texture 
    free(); 
    //The final texture 
    SDL_Texture *l_newTexture = NULL; 

    //Load image at specified path 
    SDL_Surface *l_loadedSurface = IMG_Load(path.c_str()); 
    if(l_loadedSurface == NULL) { 
    printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(),  IMG_GetError()); 
    } else { 
    //Color key image for transparancy 
    //SDL_SetColorKey(l_loadedSurface, SDL_TRUE, SDL_MapRGB(l_loadedSurface->format, 0, 0xFF, 0xFF)); 
    //Create texture from surface pixels 
    l_newTexture = SDL_CreateTextureFromSurface(g_renderer, l_loadedSurface); 

    if(l_newTexture == NULL) { 
     printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); 
    } else { 
     //Get image dimensions 
     m_width = l_loadedSurface->w; 
     m_height = l_loadedSurface->h; 
    } 
    //Get rid of old loaded surface 
    SDL_FreeSurface(l_loadedSurface); 
    } 
    m_texture = l_newTexture; 
    //return success 
    printf("end from file \n"); 

    return m_texture != NULL; 
} 

void myTexture::free() { 
    printf("In myTexture::free\n"); 
    //Free texture if it exist 
    if(m_texture != NULL) { 
    cout << (m_texture != NULL) << endl; 
    SDL_DestroyTexture(m_texture); 
    printf("Destroyed m_texture\n"); 
    m_texture = NULL; 
    m_width = 0; 
    m_height = 0; 
    } 
    printf("end free\n"); 
} 

阅读SDL和其他东西后,我明白,可能有一些线程试图解除分配的东西,它是不允许解除分配。不过,我还没有任何线程。

+0

'm_texture'初始化为'myTexture'构造函数中的空指针吗? – rems4e 2014-09-26 09:09:34

+0

是的,这里是构造函数 myTexture :: myTexture(){ //初始化 m_texture = NULL; m_width = 0; m_height = 0; } – Redhat 2014-09-26 09:34:11

+0

在开始修改它之前,它是否像LazyFoo的教程中显示的那样工作? – Zammalad 2014-09-26 10:48:03

回答

0

我设法解决这个由我自己。事实证明,我从来没有创建一个真正愚蠢的新的myTexture对象。但我仍然不明白它是如何设法使它有时......对我而言,它根本没有任何意义。我从来没有创建它,但我仍然可以有时调用它的渲染函数...