Question about Boost.Asio

As I was reading the documentation and I noticed that you can only send data that is continuously allocated (such as a plain C style array of characters).

My question is, how would I go about sending and receiving an object of a user-defined type? (such as:)

1
2
3
4
5
6
7
#include <vector>
#include <pair>

class A
{
    std::vector<std::pair<int, std::vector<char>> data;
};


Sure I could convert an pointer to an object of type A to a void*, but the data is not continuous in memory.

This is how I picture the memory structure of an object of type A:
http://postimg.org/image/fwvo47ogd/
Last edited on
Class members are continuously allocated (but some of the members could be pointers pointing to another memory areas)

Sending and receivin should be handled as reading and writing from file: you need a method to convert your class to platform-agnostic sequence of binary digits. This process is called serialization.
For example structure of your serialized class might be:
4 bytes of unsigned big endian (network order) number denoting number of elements in outer vector (X)
X entries of outer vector elements
Each element:
4 bytes of signed big endian number (first element of pair)
4 bytes of unsigned big endian number denoting number of elements in intter vector (Y)
Y entries of char (1 byte)
 
You will need to make sure that actual vector sizes/values of int is not larger than serialized value can hold and that your vector/int can hold deserialized value.
Stringify the object and send the sequence of characters. Unstringify at the other end.
Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct A
{
    std::vector< std::pair< int, std::vector<char> > > data;
};

std::string stringify( const A& a )
{
    std::ostringstream stm ;

    for( const auto& pair : a.data ) // for each pair
    {
        stm << pair.first << '\n' ; // int, newline
        for( char c : pair.second ) stm << c ; // vector of chars
        stm << '\n' ; // newline (assumes that the sequence of char does not contain newline)
    }
    stm << '\n' ; // end with a double newline

    return stm.str() ;
}

A from_string( const std::string& stringified ) ; // TODO 


For something more elaborate,
http://www.boost.org/doc/libs/1_57_0/libs/serialization/doc/index.html
@MiiNiPaa
@JLBorges

Thank you so much!
Topic archived. No new replies allowed.