Serialization of struct

后端 未结 5 1227
野性不改
野性不改 2020-11-30 05:12

Suppose i have a struct whose member values i want to send over the network to another system using winsock 2. I\'m using C++ language. How do i convert it to char * keepin

5条回答
  •  被撕碎了的回忆
    2020-11-30 05:57

    You can just do

    struct MyStruct {
    
        int data;
        char* someNullTerminatedName; // Assuming not larger than 1023 chars
    
        std::ostream& serialize(std::ostream& os) const {
            char null = '\0';
            os.write((char*)&data, sizeof(data));
            os.write(someNullTerminatedName, strlen(someNullTerminatedName));
            os.write(&null, 1);
            return os;
        }
        std::istream& deserialize(std::istream& is) {
            char buffer[1024];
            int i = 0;
            is.read((char*)&data, sizeof(data));
            do { buffer[i] = is.get(); ++i; } while(buffer[i] != '\0');
            if (someNullTerminatedName != NULL) free(someNullTerminatedName);
            someNullTerminatedName = (char*)malloc(i);
            for (i = 0; buffer[i] != '\0'; ++i) {
                someNullTerminatedName[i] = buffer[i];
            }
            return is;
        }
    };
    

    It's up to you to take care of endianness and differences in size of ints and whatnot.

    Example:

    MyStruct foo, bar;
    std::stringstream stream;
    foo.serialize(stream);
    // ... Now stream.str().c_str() contains a char* buffer representation of foo.
    // For example it might contain [ 1f 3a 4d 10 h e l l o w o r l d \0 ]
    bar.deserialize(stream);
    // ... Now bar is a copy, via a serial stream of data, of foo.
    

    If you have a socket library that exposes its interface via C++ iostreams then you don't even need the stringstream.

提交回复
热议问题