Serialization/Deserialization of a struct to a char* in C

前端 未结 7 2005
清歌不尽
清歌不尽 2020-12-05 06:21

I have a struct

struct Packet {
    int senderId;
    int sequenceNumber;
    char data[MaxDataSize];

    char* Serialize() {
        char *message = new ch         


        
相关标签:
7条回答
  • 2020-12-05 06:52

    To answer your question generally, C++ has no reflection mechanism, and so manual serialize and unserialize functions defined on a per-class basis is the best you can do. That being said, the serialization function you wrote will mangle your data. Here is a correct implementation:

    char * message = new char[MaxMailSize];
    int net_senderId = htonl(senderId);
    int net_sequenceNumber = htonl(sequenceNumber);
    memcpy(message, &net_senderId, sizeof(net_senderId));
    memcpy(message + sizeof(net_senderId), &net_sequenceNumber, sizeof(net_sequenceNumber));
    
    0 讨论(0)
提交回复
热议问题