msgpack 可以将结构转变成字符串, 然后又可以将字符串还原
官网地址: https://msgpack.org/
以下是代码, 只需要定义宏, 然后include就搞定了, 相比jason或xml都更简单易用,
节省内存, 也节省代码, 简化打包, 轻量化. 相比protobuf, 这个msgpack使用起来也更简便.
#define MSGPACK_DEFAULT_API_VERSION 1
#include <msgpack.hpp>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
struct Foo
{
int i;
string str;
msgpack::type::raw_ref data;
MSGPACK_DEFINE(i, str, data);
};
int main(int argc, char** argv)
{
Foo f;
f.i = 4;
f.str = "hello world";
const char* tmp = "msgpack";
f.data.ptr = tmp;
f.data.size = strlen(tmp) + 1;
msgpack::sbuffer sbuf;
msgpack::pack(sbuf, f);
msgpack::unpacked unpack;
msgpack::unpack(&unpack, sbuf.data(), sbuf.size());
msgpack::object obj = unpack.get();
Foo f2;
obj.convert(&f2);
cout << f2.i << ", " << f2.str << ", ";
cout << f2.data.ptr << endl;
return 0;
}