【问题标题】:SDL Error while Creating Window?创建窗口时出现 SDL 错误?
【发布时间】:2018-07-11 23:22:45
【问题描述】:
#include<SDL2/SDL.h>
#include<stdio.h>
#include<stdbool.h>

bool init(char *title, int width, int height);
void close();

SDL_Window *window = NULL;
SDL_Surface *screen = NULL;

bool init(char *title, int width, int height){

    bool success = true;

// SDL_Init 0 on success and returns negative on failure
   if( SDL_Init(SDL_INIT_EVERYTHING) != 0 ){
       SDL_Log("Couldn't initialize SDL: %s",SDL_GetError());
       success = false;
   }

// creating Window and Surface
  window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN );


// SDL_CreateWindow returns window on creation and NULL on failure
    if ( !window ){
        SDL_Log("Couldn't create window: %s",SDL_GetError());
        success = false;
    } else {
        // get window surface
        screen = SDL_GetWindowSurface( window );
        if ( screen == NULL ){
            SDL_Log("Couldn't get window surface: %s",SDL_GetError());
            success = false;
        }
    }
    return success;
}

void close(){
    // deallocate surface
    SDL_FreeSurface( screen );
    // destroy window
    SDL_DestroyWindow( window );
    // SDL_Quit();
    SDL_Quit();
}

int main(){
    bool running  = true;
    SDL_Event event;
    if( init("My Window", 800, 600) ){
       printf("Congrats\n");
    } else {
        printf("Sorry :(\n");
    }

   while( running ) {
      //  start = SDL_GetTicks();
        while ( SDL_PollEvent( &event ) ){
            switch( event.type ){
                case SDL_QUIT:
                    running = false;
                    break;
            }
        SDL_UpdateWindowSurface( window );
        }
    }

    close();
}

我尝试创建一个单独的函数来初始化 SDL 窗口,然后尝试将表面附加到它,但它给出了Segmentation fault (core dumped)。有时它也会给出错误Info: invalid window

如果我不创建单独的函数并仅在主函数中运行此代码,它可以工作!

【问题讨论】:

  • 你为什么在SDL_GetWindowSurface() 给你的SDL_Surface* 上打电话给SDL_FreeSurface()"This surface will be freed when the window is destroyed. Do not free this surface."
  • 这段代码是怎么编译的,有没有一些编译痕迹?
  • @genpfault 我做了但同样的错误。
  • 永远不要将自己的函数定义为与libc close 别名的怪异close(为了让事情更有趣,这是一个弱符号)。或者至少让你的函数static
  • @genpfault 是的,这个问题一次又一次地被问到,因为lazyfoo 教程非常受欢迎,并将它们的函数命名为close,但使用 C++(带有 mangling),所以这不是问题。

标签: c segmentation-fault sdl sdl-2


【解决方案1】:

你忘了实现一个关键功能:

SDL_BlitSurface( SDL_Surface* ,const SDL_Rect* , SDL_Surface* , SDL_Rect* );

这个函数可以blit表面并将数据(图形信息)加载到SDL_Surface结构中。

如果您想了解更多关于此功能的详细信息,可以查看链接。

链接:https://wiki.libsdl.org/SDL_BlitSurface

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2017-06-03
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多