Skip to content

v2_0_cpp_tutorial

Takatoshi Kondo edited this page Apr 9, 2018 · 12 revisions

Tutorial

How to compile

msgpack-c is a header only library. You can just add msgpack-c/include to the compiler include path.

g++ -Ipath_to_msgpack-c/include your_source.cpp

Checking the version

In order to use msgpack-c, you need to include msgpack.hpp in your source code. It is a convenience header file that contains all msgpack-c functionalities.

After include the header file, I recommend checking the version of msgpack-c.

Here is an example:

#include <iostream>

#include <msgpack.hpp>

int main() {
    std::cout << MSGPACK_VERSION << std::endl;
}

https://wandbox.org/permlink/9g8uhDsVHAW1rpwV

Because some environment often has installed older-version of the msgpack-c in /usr/include. It is very confusing. So I recommend the version of msgpack-c that actually you include.

Packing

Single value

Let's pack the small string "compact". Pack means encoding C++ types to MessagePack format data. Here is an example:

#include <iostream>
#include <sstream>

#include <msgpack.hpp>

// hex_dump is not a part of msgpack-c. 
inline std::ostream& hex_dump(std::ostream& o, std::string const& v) {
    std::ios::fmtflags f(o.flags());
    o << std::hex;
    for (auto c : v) {
        o << "0x" << std::setw(2) << std::setfill('0') << (static_cast<int>(c) & 0xff) << ' ';
    }
    o.flags(f);
    return o;
}

int main() {
    std::stringstream ss;
    msgpack::pack(ss, "compact");
    hex_dump(std::cout, ss.str()) << std::endl;
}

https://wandbox.org/permlink/c6oFGZWtYiGNF8f6

You get the following output:

0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 

A7 means 7 bytes string. And the body of the string continues. See https://msgpack.org/

This is a string example. Other types are mapped as documented here.

Aggregate value

Arrays

You can pack std::vector as follows:

int main() {
    std::stringstream ss;
    std::vector<int> v { 1, 5, 8, 2, 6 };
    msgpack::pack(ss, v);
    hex_dump(std::cout, ss.str()) << std::endl;
}

https://wandbox.org/permlink/ZB2aAMOgRRQ2Mzvc

Output:

0x95 0x01 0x05 0x08 0x02 0x06 
  A     1    5    8    2    6
  |
  5 length array

Other sequential containers can be packed in the same way.

Maps

You can pack std::map as follows:

int main() {
    std::stringstream ss;
    std::map<std::string, int> v { { "ABC", 5 }, { "DEFG", 2 } };
    msgpack::pack(ss, v);
    hex_dump(std::cout, ss.str()) << std::endl;
}

https://wandbox.org/permlink/4ZiGGpxYZ9eeRlBF

Output:

0x82 0xa3 0x41 0x42 0x43 0x05 0xa4 0x44 0x45 0x46 0x47 0x02 
  A    A   'A'  'B'  'C'    5   A   'D'  'E'  'F'  'G'    2  
  |    |                        |
  |    |                        |
  |    3 bytes string           4 bytes string
2 length map

Other associative containers can be packed in the same way.