指向 SDL_Texture 的指针出现分段错误

问题描述 投票:0回答:1

我一直在用 SDL 制作游戏,为了最大限度地减少意大利面条代码的数量,我一直在制作自己的函数来自动化许多 SDL 流程,其中一个是分配图片或字体的函数纹理。

问题是函数结束后,SDL_Texture变量不再起作用。

我已经能够复制该问题,并将其缩小为“测试”程序。

代码:

void func(SDL_Texture* pText, SDL_Rect* pRect, SDL_Renderer* rend){
    SDL_Surface* loadSurface = IMG_Load("pic.png");
        if(!loadSurface)
            printf("Error creating surface. - %s", SDL_GetError());

    pText = SDL_CreateTextureFromSurface(rend, loadSurface);
        if(!pText)
            printf("Error creating texture. - %s", SDL_GetError());

    SDL_FreeSurface(loadSurface);
}

int main(){
    SDL_Renderer* rend;
    SDL_Texture* pText;
    SDL_Rect pRect;

    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0){
        printf("error initializing SDL: %s\n", SDL_GetError());
        return 1;
    }
    SDL_Window* win = SDL_CreateWindow("app", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 250, 250, 0);
    rend = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE);

    func(pText, &pRect, rend); // test function

    int x, y;
    SDL_QueryTexture(pText, NULL, NULL, &x, &y); //Get texture size (program will either crash or print nonsense values.)

    printf("C: %d, y: %d\n", x, y);
    printf("Hang in there...");

    return 0;
}

- Compiled with G++, SDL2 dynamic (using .dll and .so)
c++ pointers segmentation-fault
1个回答
0
投票

编辑:

找到了解决方案,问题是通过传递 SDL_Texture* 指针指向的地址不会被修改,这正是我们实际需要的。 为了解决这个问题,我只是将 SDL_Texture** 和 &pText 传递给函数。

void func(SDL_Texture** pText, SDL_Rect* pRect, SDL_Renderer* rend){
    SDL_Surface* loadSurface = IMG_Load("pic.png");
        if(!loadSurface)
            printf("Error creating surface. - %s", SDL_GetError());

    *pText = SDL_CreateTextureFromSurface(rend, loadSurface);
        if(!pText)
            printf("Error creating texture. - %s", SDL_GetError());

    SDL_FreeSurface(loadSurface);
}

int main(){
    SDL_Renderer* rend;
    SDL_Texture* pText;
    SDL_Rect pRect;

    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0){
        printf("error initializing SDL: %s\n", SDL_GetError());
        return 1;
    }
    SDL_Window* win = SDL_CreateWindow("app", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 250, 250, 0);
    rend = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE);

    func(&pText, &pRect, rend); // test function

    int x, y;
    SDL_QueryTexture(pText, NULL, NULL, &x, &y); //Get texture size (now works)

    printf("C: %d, y: %d\n", x, y);
    printf("Hang in there...");

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.