简体   繁体   中英

Binary Serialization Using Boost and uint8_t

When working with binary data I tend to use uint8_t . I guess that just seems like the type of a byte to me. However, I can't figure out how to get the binary serialization in boost to work with that type. Am I asking the impossible or just missing something simple?

This example program doesn't compile on VS2013 with some complaint about not being about to convert the streams into std::ostream or std::istream .

The program works fine with char instead of uint8_t , but that bugs me. :)

#include <cstdlib> // EXIT_SUCCESS
#include <vector>

#include "boost/archive/binary_iarchive.hpp"
#include "boost/archive/binary_oarchive.hpp"
#include "boost/iostreams/device/array.hpp"
#include "boost/iostreams/device/back_inserter.hpp"
#include "boost/iostreams/stream_buffer.hpp"

int main(int argc, char** argv)
{
   typedef std::vector< uint8_t > Buffer;
   Buffer buffer;

   // Serialization
   {
      int foo = 1;

      typedef boost::iostreams::back_insert_device< Buffer > Device;
      Device device(buffer);

      typedef boost::iostreams::stream_buffer< Device > Stream;
      Stream stream(device);

      {
         boost::archive::binary_oarchive archive(stream);
         archive << foo;
      }
   }

   // Deserialization
   {
      int foo;

      typedef boost::iostreams::basic_array_source< uint8_t > Device;
      Device device(buffer.data(), buffer.size());

      typedef boost::iostreams::stream_buffer< Device > Stream;
      Stream stream(device);

      {
         boost::archive::binary_iarchive archive(stream);
         archive >> foo;
      }
   }

   return EXIT_SUCCESS;
}

The binary archives take a std::istream / std::ostream argument, so you're stuck using std::basic_istream<char> / std::basic_ostream<char> .

Incidentally there's no guarantee that implementations offer unsigned char / uint8_t versions of streams (or rather std::char_traits<unsigned char> ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM