c++ - Serialization of struct -
suppose have struct member values want send on network system using winsock 2. i'm using c++ language. how convert char * keeping in mind struct has serialized before sending , how deserialize char * struct @ other end? found boost serialization suggestion similar question can illustrate small code snippet both serialization , deserialization ?
this question might seem basic other answers related posts did not much.
following example shows simplest way serialize struct
char
array , de-serialize it.
#include <iostream> #include <cstring> #define bufsize 512 #define packetsize sizeof(msg) using namespace std; typedef struct msg { int type; int priority; int sender; char message[bufsize]; }msg; void serialize(msg* msgpacket, char *data); void deserialize(char *data, msg* msgpacket); void printmsg(msg* msgpacket); int main() { msg* newmsg = new msg; newmsg->type = 1; newmsg->priority = 9; newmsg->sender = 2; strcpy(newmsg->message, "hello server\0"); printmsg(newmsg); char data[packetsize]; serialize(newmsg, data); msg* temp = new msg; deserialize(data, temp); printmsg(temp); return 0; } void serialize(msg* msgpacket, char *data) { int *q = (int*)data; *q = msgpacket->type; q++; *q = msgpacket->priority; q++; *q = msgpacket->sender; q++; char *p = (char*)q; int = 0; while (i < bufsize) { *p = msgpacket->message[i]; p++; i++; } } void deserialize(char *data, msg* msgpacket) { int *q = (int*)data; msgpacket->type = *q; q++; msgpacket->priority = *q; q++; msgpacket->sender = *q; q++; char *p = (char*)q; int = 0; while (i < bufsize) { msgpacket->message[i] = *p; p++; i++; } } void printmsg(msg* msgpacket) { cout << msgpacket->type << endl; cout << msgpacket->priority << endl; cout << msgpacket->sender << endl; cout << msgpacket->message << endl; }
Comments
Post a Comment