Created
January 13, 2010 09:43
-
-
Save osaboh/276074 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// messagepack-0.3.9 exsample for C | |
// http://msgpack.sourceforge.jp/ | |
// http://msgpack.sourceforge.jp/c:doc.ja (C API) | |
/* | |
$ make | |
gcc msgpack.c -o msgpack -lmsgpackc | |
$ ldd ./msgpack | |
linux-gate.so.1 => (0xffffe000) | |
libmsgpackc.so.1 => /usr/local/lib/libmsgpackc.so.1 (0xb7f0d000) | |
libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7dd9000) | |
/lib/ld-linux.so.2 (0xb7f27000) | |
*/ | |
#include <msgpack.h> | |
#include <stdio.h> | |
int main(void) | |
{ | |
/* msgpack::sbuffer is a simple buffer implementation. */ | |
// 「シンプルバッファ」の作成 | |
msgpack_sbuffer sbuf; | |
msgpack_sbuffer_init(&sbuf); | |
/* serialize values into the buffer using msgpack_sbuffer_write callback function. */ | |
/* | |
シリアライザの初期化 | |
callback (-> msgpack_sbuffer_write)はシリアライズ関数(msgpack_push_XXX)を | |
呼び出したときに、dataで指定されたポインタと、シリアライズするバイト列と | |
バイト列の長さを引数として呼び出されます。 | |
*/ | |
msgpack_packer pk; | |
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write); | |
/* | |
n個の要素を含む配列のヘッダをシリアライズします。 | |
この後に続くn個のオブジェクトが配列の要素になります。 | |
*/ | |
msgpack_pack_array(&pk, 3); | |
/* | |
XXX型の変数をシリアライズします。 | |
指定された変数を格納するのに都合の良い保存形式でシリアライズされます。 | |
*/ | |
msgpack_pack_int(&pk, 1); | |
msgpack_pack_true(&pk); | |
/* | |
l(->7)バイトのバイト列のヘッダをシリアライズします。 | |
この後に続く合計lバイト分のmsgpack_pack_raw_bodyの呼び出しがバイト列の要素になります。 | |
*/ | |
msgpack_pack_raw(&pk, 7); | |
// bで示されるポインタからl(->7)バイト分だけバイト列をシリアライズします。 | |
msgpack_pack_raw_body(&pk, "example", 7); | |
/* deserialize the buffer into msgpack_object instance. */ | |
/* deserialized object is valid during the msgpack_zone instance alive. */ | |
/* | |
msgpack_zoneはシングルスレッドに特化したメモリプールの実装です。 | |
複数のスレッドから同時にメモリ確保できない代わりに、 | |
malloc(3)よりも圧倒的に高速にメモリを確保することができます。 | |
ゾーンを解放すると、そのゾーンから確保していたメモリは全部解放されます。 | |
*/ | |
msgpack_zone mempool; | |
msgpack_zone_init(&mempool, 2048); | |
/* | |
dataで指定されたバイト列を最大lenバイトまでデシリアライズします。 | |
z(->mempool)には初期化された自動解放ゾーンを指定します。 | |
*/ | |
msgpack_object deserialized; | |
msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized); | |
/* print the deserialized object. */ | |
// オブジェクトを読みやすいように整形して、outに指定されたストリームに出力します。 | |
msgpack_object_print(stdout, deserialized); | |
puts(""); | |
// msgpack_zone_initで作成したゾーンを解放します。 | |
msgpack_zone_destroy(&mempool); | |
// msgpack_sbuffer_initで作成したバッファを破棄します。 | |
msgpack_sbuffer_destroy(&sbuf); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment