Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize and send a data structure using Boost?

Tags:

I have a data structure that looks like this:

 typedef struct {   unsigned short m_short1;   unsigned short m_short2;   unsigned char m_character; } MyDataType; 

I want to use boost::serialization to serialize this data structure, then use boost::asio to transmit it via TCP/IP, then have another application receive the data and de-serialize it using the same boost libraries.

I'm trying to following boost::serialization tutorial, (as some other SO questions have suggested) but the example is specifically for writing/reading to a file, not to a socket using boost::asio.

I'm pretty sure I've got the right tools for the job -- I just need help making them work together. Writing to a socket can't be that different from writing to a file, right?

Any suggestions are very much appreciated. Thanks!

like image 597
Runcible Avatar asked Mar 16 '09 21:03

Runcible


People also ask

How do you serialize an object in C++?

Serializing whole objects To unserialize an object, it should have a constructor that takes byte stream. It can be an istream but in the simplest case it can be just a reference uint8_t pointer. The constructor reads the bytes it wants from the stream and sets up the fields in the object.

What is serialization in C++?

Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after execution of a program.

What is serialization used for?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


2 Answers

There is a good serialization example in the asio documentation: server.cpp, stock.hpp, connection.hpp.

Here's a snippet:

std::ostringstream archive_stream; boost::archive::text_oarchive archive(archive_stream); archive << your_struct; outbound_data_ = archive_stream.str(); boost::asio::async_write(socket_,      boost::asio::buffer(outbound_data_), handler); 
like image 149
hvintus Avatar answered Oct 06 '22 01:10

hvintus


I thought I'd share this with anyone who was trying to serialize a C++ struct using Boost. For the example given above, to make the struct serializable you would add a serialize function:

typedef struct {   unsigned short m_short1;   unsigned short m_short2;   unsigned char m_character;    template <typename Archive>   void serialize(Archive& ar, const unsigned int version)   {     ar & m_short1;     ar & m_short2;     ar & m_character;   } } MyDataType; 
like image 21
Tymek Avatar answered Oct 06 '22 01:10

Tymek