In software development, it's often necessary to read data from memory buffers without copying or altering their contents. One such scenario is when the data is stored in a constant character pointer (const char*). To enable convenient reading from such buffers, creating an input stream is a viable solution.
A custom stream buffer can facilitate the creation of an input stream from immutable memory. Here's how to implement it:
#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)) { } };
The const_cast
Once the stream buffer is created, you can use it to initialize an input stream and read data from the buffer:
imemstream in(data, size); int x; float y; std::string w; in >> x >> y >> w;
The above is the detailed content of How can I create an input stream from immutable memory?. For more information, please follow other related articles on the PHP Chinese website!