[英]Reading SDL_RWops from a std::istream
我很惊讶Google没有找到解决方案。 我正在寻找一种允许SDL_RWops与std :: istream一起使用的解决方案。 SDL_RWops是在SDL中读/写数据的替代机制。
是否有指向解决问题的网站的链接?
一个明显的解决方案是预先读取足够的数据到内存,然后使用SDL_RWFromMem。 但是,这有一个缺点,我需要事先知道文件大小。
似乎可以通过“覆盖”SDL_RWops函数以某种方式解决问题......
我回答自己的问题感觉很糟糕,但它已经让我好一段时间,这就是我提出的解决方案:
int istream_seek( struct SDL_RWops *context, int offset, int whence)
{
std::istream* stream = (std::istream*) context->hidden.unknown.data1;
if ( whence == SEEK_SET )
stream->seekg ( offset, std::ios::beg );
else if ( whence == SEEK_CUR )
stream->seekg ( offset, std::ios::cur );
else if ( whence == SEEK_END )
stream->seekg ( offset, std::ios::end );
return stream->fail() ? -1 : stream->tellg();
}
int istream_read(SDL_RWops *context, void *ptr, int size, int maxnum)
{
if ( size == 0 ) return -1;
std::istream* stream = (std::istream*) context->hidden.unknown.data1;
stream->read( (char*)ptr, size * maxnum );
return stream->bad() ? -1 : stream->gcount() / size;
}
int istream_close( SDL_RWops *context )
{
if ( context ) {
SDL_FreeRW( context );
}
return 0;
}
SDL_RWops *SDL_RWFromIStream( std::istream& stream )
{
SDL_RWops *rwops;
rwops = SDL_AllocRW();
if ( rwops != NULL )
{
rwops->seek = istream_seek;
rwops->read = istream_read;
rwops->write = NULL;
rwops->close = istream_close;
rwops->hidden.unknown.data1 = &stream;
}
return rwops;
}
在假设的情况下工作从未被SDL释放(并且他们通过操作生活)。 也只有istream支持,ostream会做一个单独的函数 - 我知道我可以传递iostream,但是这不允许将istream传递给转换函数:/。
有关错误或升级的任何提示都欢迎。
如果您尝试从istream获取SDL_RWops结构,可以通过将整个istream读入内存然后使用SDL_RWFromMem来获取表示它的结构来实现。
以下是一个简单的例子; 请注意,这是不安全的,因为没有进行健全性检查。 例如,如果文件的大小为0,则访问缓冲区[0]可能会在调试版本中引发异常或断言。
// Open a bitmap
std::ifstream bitmap("bitmap.bmp");
// Find the bitmap file's size
bitmap.seekg(0, std::ios_base::end);
std::istream::pos_tye fileSize = bitmap.tellg();
bitmap.seekg(0);
// Allocate a buffer to store the file in
std::vector<unsigned char> buffer(fileSize);
// Copy the istream into the buffer
std::copy(std::istreambuf_iterator<unsigned char>(bitmap), std::istreambuf_iterator<unsigned char>(), buffer.begin());
// Get an SDL_RWops struct for the file
SDL_RWops* rw = SDL_RWFromMem(&buffer[0], buffer.size());
// Do stuff with the SDL_RWops struct
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.