SDL 包含许多处理以 SDL_RWops 结构为中心的 I/O 的函数。它们中的很多都与 stdio I/O 函数非常相似,以至于它们使用相同样式的字符串。例如,fopen 与 SDLRWFromfile。
为什么会出现这种情况?我是否应该针对标准库使用 SDL I/O 函数? SDL 功能是否更便携?
请您参考如下方法:
SDL_RWops
的兴趣是它只是一个接口(interface)结构,带有用于读取/写入/查找/关闭的函数指针...
typedef struct SDL_RWops {
/** Seek to 'offset' relative to whence, one of stdio's whence values:
* SEEK_SET, SEEK_CUR, SEEK_END
* Returns the final offset in the data source.
*/
int (SDLCALL *seek)(struct SDL_RWops *context, int offset, int whence);
/** Read up to 'maxnum' objects each of size 'size' from the data
* source to the area pointed at by 'ptr'.
* Returns the number of objects read, or -1 if the read failed.
*/
int (SDLCALL *read)(struct SDL_RWops *context, void *ptr, int size, int maxnum);
/** Write exactly 'num' objects each of size 'objsize' from the area
* pointed at by 'ptr' to data source.
* Returns 'num', or -1 if the write failed.
*/
int (SDLCALL *write)(struct SDL_RWops *context, const void *ptr, int size, int num);
/** Close and free an allocated SDL_FSops structure */
int (SDLCALL *close)(struct SDL_RWops *context);
// ... there are other internal fields too
}
例如使用
SDL_LoadBMP
时, SDL 创建一个
SDL_RWops
来自文件句柄的对象,但您也可以创建
SDL_RWops
来自其他来源的对象,例如内存位置,例如对于不提供 native 文件系统的系统(想到 Nintendo DS,即使像 R4 或 M3 这样的自制链接器推车通常能够提供这样的服务)。
来自
SDL_Video.h
:
/**
* Load a surface from a seekable SDL data source (memory or file.)
...
*/
extern DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_RW(SDL_RWops *src, int freesrc);
/** Convenience macro -- load a surface from a file */
#define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1)
所以
SDL_LoadBMP
是一个调用
SDL_RWFromFile(file, "rb")
的宏,它当然使用标准库来创建文件句柄并创建
SDL_RWop
函数指针初始化为现有标准库的对象
read
,
write
,
seek
,
close
职能。
在这种情况下,您可以将您的 Assets 硬编码在可执行二进制文件中作为字节数组,并映射一个
SDL_RWops
该内存上的对象。
因此,对于 SDL 函数,您必须使用它们(即使它们的使用是隐藏的)。但是,如果您有其他资源文件(如音频、配置文件)没有提供给 SDL,则可以使用标准库来读取它们。