Skip to content

Instantly share code, notes, and snippets.

@mizutomo
Created June 7, 2010 03:04
Show Gist options
  • Save mizutomo/428179 to your computer and use it in GitHub Desktop.
Save mizutomo/428179 to your computer and use it in GitHub Desktop.
MessagePackによる参照型のシリアライズ/デシリアライズ
#include <msgpack.hpp>
#include <vector>
#include <map>
#include <iostream>
#include <cstdio>
struct point_t {
float x;
float y;
float z;
MSGPACK_DEFINE(x, y, z);
};
class cube_t {
public:
point_t& p1;
point_t& p2;
point_t& p3;
cube_t(point_t& _p1, point_t& _p2, point_t& _p3) : p1(_p1), p2(_p2), p3(_p3) {;}
MSGPACK_DEFINE(p1, p2, p3);
};
void serialize(const char* filename)
{
// This is target object.
point_t p1, p2, p3;
p1.x = 1; p1.y = 2; p1.z = 3;
p2.x = 4; p2.y = 5; p2.z = 6;
p3.x = 7; p3.y = 8; p3.z = 9;
cube_t cube(p1, p2, p3);
// Serialize it.
msgpack::sbuffer buffer; // simple buffer
msgpack::pack(&buffer, cube);
FILE* fp;
fp = fopen(filename, "wb");
fwrite(buffer.data(), buffer.size(), 1, fp);
fclose(fp);
}
void deserialize(const char* filename)
{
char buf[1024];
FILE* fp;
fp = fopen(filename, "rb");
ssize_t size = fread(buf, sizeof(buf[0]), 1024, fp);
msgpack::zone z;
msgpack::object obj;
msgpack::unpack(buf, size, NULL, &z, &obj);
std::cout << "pretty print: " << obj << std::endl;
try {
point_t p1, p2, p3;
cube_t data(p1, p2, p3);
obj.convert(&data);
printf("P1: %f, %f, %f\n", data.p1.x, data.p1.y, data.p1.z);
printf("P2: %f, %f, %f\n", data.p2.x, data.p2.y, data.p2.z);
printf("P3: %f, %f, %f\n", data.p3.x, data.p3.y, data.p3.z);
} catch(msgpack::type_error& e) {
std::cout << "type mismatch. std::vector<std::striang> is expected"
<< std::endl;
}
}
int main(int argc, char** argv)
{
const char* filename = "msgpack.txt";
serialize(filename);
deserialize(filename);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment