Skip to content

Using MsgPack in CPP

Programming / cpp / libraries

Install

sudo apt install libmsgpack-dev

magpack-c

Demo:

Header only

#include <iostream>
#include <msgpack.hpp>
#include <vector>
#include <string>

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

    // 1️⃣ Create some data
    std::vector<std::string> items = {"apple", "banana", "cherry"};

    // 2️⃣ Pack (serialize) data to binary buffer
    msgpack::sbuffer buffer; // simple buffer
    msgpack::pack(buffer, items);

    // 3️⃣ Unpack (deserialize) data
    msgpack::object_handle handle = msgpack::unpack(buffer.data(), buffer.size());
    msgpack::object deserialized = handle.get();

    // 4️⃣ Convert msgpack::object back to C++ type
    std::vector<std::string> unpacked;
    deserialized.convert(unpacked);

    // 5️⃣ Print the results
    std::cout << "Unpacked vector: ";
    for (auto &s : unpacked) std::cout << s << " ";
    std::cout << std::endl;

    return 0;
}
g++ -I/usr/include demo.cpp -o demo

cmake

cmake_minimum_required(VERSION 3.10)
project(msgpack_define_map_example)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Msgpack REQUIRED)

add_executable(msgpack_example demo.cpp)
target_include_directories(msgpack_example PRIVATE  ${MSGPACK_INCLUDE_DIRS})

pack struct

#include <iostream>
#include <msgpack.hpp>

struct Point
{
    int x;
    int y;

    MSGPACK_DEFINE(x, y);
};

int main()
{
    Point p{10, 20};
    msgpack::sbuffer buf;
    msgpack::pack(buf, p);

    auto handle = msgpack::unpack(buf.data(), buf.size());
    msgpack::object obj = handle.get();

    Point p2;
    obj.convert(p2);
    std::cout << "Point: (" << p2.x << ", " << p2.y << ")\n";
    return 0;
}