python版本的msgpack非常好用,速度上比python內置的pickle和cpickle都要快一些,C++版本的使用比較麻煩,下面是本人學習時的一個example,解析python-msgpack dump的一個復雜字典。
- #include <msgpack.hpp>
-
- #include <fstream>
- #include <iostream>
- using namespace std;
-
- template <class T>
- void msgunpack(const char* binary_file, T& t, char* buff, uint32_t max){
- msgpack::unpacked msg;
- ifstream tf_file(binary_file,ios::in|ios::binary|ios::ate);
- uint32_t size = tf_file.tellg();
- tf_file.seekg(0, ios::beg);
- tf_file.read(buff, size);
- tf_file.close();
- msgpack::unpack(&msg, buff, size);
- msg.get().convert(&t);
- }
-
-
- typedef map<uint32_t, uint32_t> WordsMap;
- typedef map<uint32_t, WordsMap> FieldsMap;
- typedef map<uint64_t, FieldsMap> DocsMap;
-
- int main(int argc, char** argv)
- {
- uint32_t MAX_BUFF = 1024*1024*100; //100MB
- char* BUFF = new char[MAX_BUFF];
-
- DocsMap docsMap;
- msgpack::unpacked msg;
- msgunpack("/data/wikidoc/tf_dict_for_nodes/1-1000", docsMap, BUFF, MAX_BUFF);
- // msg.get().convert(&docsMap);
- cout << docsMap.size() << endl;
- delete[] BUFF;
- }
參考: http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387#QuickStartforC%2B%2B-ImplementationStatus
下面是本人自己封裝的一個msgpack接口頭文件mymsgpack.h
- #ifndef MY_MSGPACK_H
-
- #ifndef MY_MSGPACK_H
- #define MY_MSGPACK_H
- #include <fstream>
- #include <msgpack.hpp>
- using namespace std;
-
- template <class T>
- void load_from_file(const char* binary_file, T& t) {
- ifstream binaryFstream(binary_file,ios::in|ios::binary|ios::ate);
- uint32_t size = binaryFstream.tellg();
- char* buff = new char[size];
- binaryFstream.seekg(0, ios::beg);
- binaryFstream.read(buff, size);
- binaryFstream.close();
- msgpack::unpacked msg;
- msgpack::unpack(&msg, buff, size);
- msg.get().convert(&t);
- delete[] buff;
- }
-
- template <class T>
- void load_from_str(const char* binary_str, int len, T& t) {
- msgpack::unpacked msg;
- msgpack::unpack(&msg, binary_str, len);
- msg.get().convert(&t);
- }
-
- template <class T>
- void dump_to_file(T& t, const char* dump_file) {
- msgpack::sbuffer sbuf;
- msgpack::pack(sbuf, t);
- ofstream dumpFstream(dump_file, ios::out|ios::binary|ios::trunc);
- dumpFstream.write(sbuf.data(), sbuf.size());
- dumpFstream.close();
- }
-
- template <class T>
- void dump_to_str(T& t, char** dump_str, int& len) { //外部釋放*dump_str
- msgpack::sbuffer sbuf;
- msgpack::pack(sbuf, t);
- len = sbuf.size();
- *dump_str = (char*)malloc(sbuf.size());
- memcpy(*dump_str, sbuf.data(), sbuf.size());
- }
-
- #endif