simple_c.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <msgpack.h>
  2. #include <stdio.h>
  3. void print(char const* buf, unsigned int len)
  4. {
  5. size_t i = 0;
  6. for(; i < len ; ++i)
  7. printf("%02x ", 0xff & buf[i]);
  8. printf("\n");
  9. }
  10. int main(void)
  11. {
  12. msgpack_sbuffer sbuf;
  13. msgpack_packer pk;
  14. msgpack_zone mempool;
  15. msgpack_object deserialized;
  16. /* msgpack::sbuffer is a simple buffer implementation. */
  17. msgpack_sbuffer_init(&sbuf);
  18. /* serialize values into the buffer using msgpack_sbuffer_write callback function. */
  19. msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  20. msgpack_pack_array(&pk, 3);
  21. msgpack_pack_int(&pk, 1);
  22. msgpack_pack_true(&pk);
  23. msgpack_pack_str(&pk, 7);
  24. msgpack_pack_str_body(&pk, "example", 7);
  25. print(sbuf.data, sbuf.size);
  26. /* deserialize the buffer into msgpack_object instance. */
  27. /* deserialized object is valid during the msgpack_zone instance alive. */
  28. msgpack_zone_init(&mempool, 2048);
  29. msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);
  30. /* print the deserialized object. */
  31. msgpack_object_print(stdout, deserialized);
  32. puts("");
  33. msgpack_zone_destroy(&mempool);
  34. msgpack_sbuffer_destroy(&sbuf);
  35. return 0;
  36. }