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.