Skip to content

Instantly share code, notes, and snippets.

@mizutomo
Created June 7, 2010 06:34
Show Gist options
  • Save mizutomo/428296 to your computer and use it in GitHub Desktop.
Save mizutomo/428296 to your computer and use it in GitHub Desktop.
MessagePackによるenum型のシリアライズ/デシリアライズ
#include <msgpack.hpp>
#include <vector>
#include <map>
#include <iostream>
#include <cstdio>
typedef enum {
CIRCLE = 0,
SQUARE = 1,
TRIANGLE = 2
} fig_t;
class hoge {
public:
fig_t fig;
MSGPACK_DEFINE((int&)fig);
};
void serialize(const char* filename)
{
// This is target object.
std::vector<hoge> figs;
hoge circle, square;
circle.fig = CIRCLE;
square.fig = SQUARE;
figs.push_back(circle);
figs.push_back(square);
// Serialize it.
msgpack::sbuffer buffer; // simple buffer
msgpack::pack(&buffer, figs);
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 {
std::vector<hoge> data;
obj.convert(&data);
for (std::vector<hoge>::iterator it = data.begin(); it < data.end(); it++) {
std::cout << (*it).fig << std::endl;
}
} 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;
}
@mavenlin
Copy link

MSGPACK_DEFINE((int&)fig) 真赞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment