msgpack hello world in c/c++
msgpack hello world
* msgpack cplusplus api lets you build an object graph with std structuresand it will serialize it. * minimal cplusplus program to write a msgpack
================
#include
#include
#include
#include using namespace std; int main()
{
map > outer;
map inner;
inner["foo"] = 42;
inner["bar"] = 69;
outer["baz"]=inner; msgpack::sbuffer sbuf;
msgpack::pack(sbuf, outer);
cout << sbuf.data() << endl;
}
================ * compilation
g++ -lmsgpack hello_msgpack_write.cpp -o hello_msgpack_write * run
./hello_msgpack_write > x.msgpack * unpack from python
python msgpack-to-json.py x.msgpack
{
"baz": {
"foo": 42,
"bar": 69
}
} * msgpack-to-json.py
import sys
import msgpack
import json
print json.dumps(msgpack.loads(file(sys.argv[1]).read()), indent=4) * msgpack C api * packing bolierplate
msgpack_sbuffer sbuf;
msgpack_sbuffer_init(&sbuf);
msgpack_packer pk;
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write); * packing a list
msgpack_pack_array(&pk, 3);
msgpack_pack_int(&pk, 1);
msgpack_pack_true(&pk);
msgpack_pack_raw(&pk, 7);
msgpack_pack_raw_body(&pk, "example", 7); * packing a map
/*
* packing a map {"foo"=>42, "bar"=>true}
* how to pack hierarchies? like lol or list of maps?
*/
msgpack_pack_map(&pk, 2); /* must know the number of items ahead of time. */
/* key */
msgpack_pack_raw(&pk, 3); /* length prefix?? there is no pack_string? */
msgpack_pack_raw_body(&pk, "foo", 3);
/* val */
msgpack_pack_int(&pk, 42);
/* another key */
msgpack_pack_raw(&pk, 3);
msgpack_pack_raw_body(&pk, "bar", 3);
/* another val */
msgpack_pack_true(&pk); * reference: msgpack/example/simple.c in source distribution
* packing composite object
/* packing a list: [1, true, "example", {"foo"=>42, "bar"=>807}, 816] */
/* number of items must be known ahead of time */
msgpack_pack_array(&pk, 5);
msgpack_pack_int(&pk, 1);
msgpack_pack_true(&pk);
/* packing a string is tedious .. */
msgpack_pack_raw(&pk, 7);
msgpack_pack_raw_body(&pk, "example", 7);
/* map of two items */
msgpack_pack_map(&pk, 2);
/* key1 */
msgpack_pack_raw(&pk, 3);
msgpack_pack_raw_body(&pk, "foo", 3);
/* val1 */
msgpack_pack_int(&pk, 42);
/* key2 */
msgpack_pack_raw(&pk, 3);
msgpack_pack_raw_body(&pk, "bar", 3);
/* val2 */
msgpack_pack_int(&pk, 807);
/*
* element after the map.
* we know this goes into the list, not the map because
* the slots in the maps are exhausted.
*/
msgpack_pack_int(&pk, 816);