class Data { public: int var1; string var2; string var3; vector<string> var4; int serialize_length(); void serialize_buffer(char *buf); static Data deserialize(char *buf); };
int Data::serialize_length() { int l = 0; l = l + sizeof(int); l = l + 2 + var2.length(); l = l + 2 + var3.length(); l = l + 2; for(int i = 0; i < var4.size(); i++) { l = l + 2 + var4[i].length(); } return l; }
void Data::serialize_buffer(char *buf) { short tmp; int ix = 0; memcpy(buf+ix,&var1,sizeof(int)); ix = ix + sizeof(int); tmp = var2.length(); memcpy(buf+ix,&tmp,2); ix = ix + 2; memcpy(buf+ix,var2.c_str(),var2.length()); ix = ix + var2.length(); tmp = var3.length(); memcpy(buf+ix,&tmp,2); ix = ix + 2; memcpy(buf+ix,var3.c_str(),var3.length()); ix = ix + var3.length(); tmp = var4.size(); memcpy(buf+ix,&tmp,2); ix = ix + 2; for(int i = 0; i < var4.size(); i++) { tmp = var4[i].length(); memcpy(buf+ix,&tmp,2); ix = ix + 2; memcpy(buf+ix,var4[i].c_str(),var4[i].length()); ix = ix + var4[i].length(); } }
Data Data::deserialize(char *buf) { Data res; short tmp,n; char s[65536]; int ix = 0; memcpy(&res.var1,buf+ix,sizeof(int)); ix = ix + sizeof(int); memcpy(&tmp,buf+ix,2); ix = ix + 2; memcpy(s,buf+ix,tmp); ix = ix + tmp; s[tmp] = '\0'; res.var2 = s; memcpy(&tmp,buf+ix,2); ix = ix + 2; memcpy(s,buf+ix,tmp); ix = ix + tmp; s[tmp] = '\0'; res.var3 = s; memcpy(&n,buf+ix,2); ix = ix + 2; for(int i = 0; i < n; i++) { memcpy(&tmp,buf+ix,2); ix = ix + 2; memcpy(s,buf+ix,tmp); ix = ix + tmp; s[tmp] = '\0'; res.var4.push_back(s); } return res; }
int main() { Data d; d.var1 = 123; d.var2 = "abc"; d.var3 = "def"; d.var4.push_back("a"); d.var4.push_back("bb"); d.var4.push_back("ccc"); int len = d.serialize_length(); char *buf = new char[len]; d.serialize_buffer(buf); Data d2 = Data::deserialize(buf); cout << d2.var1 << endl; cout << d2.var2 << endl; cout << d2.var3 << endl; for(int i = 0; i < d2.var4.size(); i++) { cout << d2.var4[i] << endl; } return 0; }
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.