Serializing object to byte-array in C++

前端 未结 2 410
南旧
南旧 2021-01-03 00:40

I am working on an embedded device (microcontroller), and I want to save objects to permanent storage (an EEPROM). Most of the serialization solutions I can find, use the fi

2条回答
  •  佛祖请我去吃肉
    2021-01-03 01:03

    To save a string to binary, usually we save its length and then its content. To save other primitive data, we can simply store their binary form. So in your case, all you need to store is:

    Length to name
    char array of name
    age
    weight
    

    So the code to serial is:

    size_t buffer_size = sizeof(int) + strlen(name) + sizeof(age) + sizeof(weight);
    char *buffer = new char[buffer_size];
    *(int*)p = strlen(name);  p += sizeof(int);
    memcpy(p, name, strlen(name));  p += strlen(name);
    *(int*)p = age;  p += sizeof(int);
    *(float*)p = weight;
    EEPROM::Save(buffer, buffer_size);
    delete[] buffer;
    

    And to read a string from binary buffer, you read its length first, and then copy its data.

提交回复
热议问题