Simpler way to create a C++ memorystream from (char*, size_t), without copying the data? -
i couldn't find ready-made, came with:
class membuf : public basic_streambuf<char> { public: membuf(char* p, size_t n) { setg(p, p, p + n); setp(p, p + n); } }
usage:
char *mybuffer; size_t length; // ... allocate "mybuffer", put data it, set "length" membuf mb(mybuffer, length); istream reader(&mb); // use "reader"
i know of stringstream
, doesn't seem able work binary data of given length.
am inventing own wheel here?
edit
- it must not copy input data, create iterate on data.
- it must portable - @ least should work both under gcc , msvc.
i'm assuming input data binary (not text), , want extract chunks of binary data it. without making copy of input data.
you can combine boost::iostreams::basic_array_source
, boost::iostreams::stream_buffer
(from boost.iostreams) boost::archive::binary_iarchive
(from boost.serialization) able use convenient extraction >> operators read chunks of binary data.
#include <stdint.h> #include <iostream> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> #include <boost/archive/binary_iarchive.hpp> int main() { uint16_t data[] = {1234, 5678}; char* dataptr = (char*)&data; typedef boost::iostreams::basic_array_source<char> device; boost::iostreams::stream_buffer<device> buffer(dataptr, sizeof(data)); boost::archive::binary_iarchive archive(buffer, boost::archive::no_header); uint16_t word1, word2; archive >> word1 >> word2; std::cout << word1 << "," << word2 << std::endl; return 0; }
with gcc 4.4.1 on amd64, outputs:
1234,5678
boost.serialization powerful , knows how serialize basic types, strings, , stl containers. can make types serializable. see documentation. hidden somewhere in boost.serialization sources example of portable binary archive knows how perform proper swapping machine's endianness. might useful well.
if don't need fanciness of boost.serialization , happy read binary data in fread()-type fashion, can use basic_array_source
in simpler way:
#include <stdint.h> #include <iostream> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> int main() { uint16_t data[] = {1234, 5678}; char* dataptr = (char*)&data; typedef boost::iostreams::basic_array_source<char> device; boost::iostreams::stream<device> stream(dataptr, sizeof(data)); uint16_t word1, word2; stream.read((char*)&word1, sizeof(word1)); stream.read((char*)&word2, sizeof(word2)); std::cout << word1 << "," << word2 << std::endl; return 0; }
i same output program.
Comments
Post a Comment