从常量内存创建输入流 [英] Creating an input stream from constant memory

查看:120
本文介绍了从常量内存创建输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个 const char * 指针指向的缓冲区中有一些数据。数据只是一个ASCII字符串。我知道它的大小。我想能够读取数据从流中读取相同的方式。我正在寻找一个解决方案,让我写这样的代码:

I have some data in a buffer pointed to by a const char* pointer. The data is just an ASCII string. I know its size. I would like to be able to read it in the same way data is read from streams. I'm looking for a solution that would allow me to write code like this:

// for example, data points to a string "42 3.14 blah"
MemoryStreamWrapper in(data, data_size);
int x;
float y;
std::string w;
in >> x >> y >> w;

重要条件:不得以任何方式复制或更改数据 (否则我只是使用字符串流。据我所知,不可能从一个const char指针创建一个字符串流,而不复制数据。)

Important condition: the data must not be copied or altered in any way (otherwise I'd just use a string stream. To my best knowledge, it isn't possible to create a string stream from a const char pointer without copying the data.)

推荐答案

这样做的方法是创建一个合适的流缓冲区。例如,可以这样做:

The way to do this is to create a suitable stream buffer. This can, e.g., be done like this:

#include <streambuf>
#include <istream>

struct membuf: std::streambuf {
    membuf(char const* base, size_t size) {
        char* p(const_cast<char*>(base));
        this->setg(p, p, p + size);
    }
};
struct imemstream: virtual membuf, std::istream {
    imemstream(char const* base, size_t size)
        : membuf(base, size)
        , std::istream(static_cast<std::streambuf*>(this)) {
    }
};

唯一有点尴尬的是 const_cast< char *> 在流缓冲区中:流缓冲区不会改变数据,但是接口仍然需要使用 char * ,主要是为了更容易以改变正常流缓冲器中的缓冲器。这样,您可以使用 imemstream 作为正常的输入流:

The only somewhat awkward thing is the const_cast<char*>() in the stream buffer: the stream buffer won't change the data but the interface still requires char* to be used, mainly to make it easier to change the buffer in "normal" stream buffers. With this, you can use imemstream as a normal input stream:

imemstream in(data, size);
in >> value;

这篇关于从常量内存创建输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆