Dealing with data serialization without violating the strict aliasing rule

前端 未结 2 528
慢半拍i
慢半拍i 2021-01-23 21:37

Often in embedded programming (but not limited to) there is a need to serialize some arbitrary struct in order to send it over some communication channel or write t

2条回答
  •  野的像风
    2021-01-23 22:16

    Just a note I am not entirely sure but it can be that it is not always safe to cast uint8_t* to char*(here).

    Regardless, what does the last parameter of your write function want, number of bytes to write - or number of uint32_t elements? Let's assume later, and also assume you want to write each member of the struct to separate integer. You can do this:

    uint32_t dest[4] = {0};
    memcpy(buffer, &s.a, sizeof(float));
    memcpy(buffer+1, &s.b, sizeof(uint8_t));
    memcpy(buffer+2, &s.c, sizeof(uint32_t));
    
    write_to_eeprom(buffer, 3 /* Nr of elements */);
    

    If you want to copy the structure elements to the integer array consecutively - you can first copy the structure member to a byte array consecutively - and then copy the byte array to the uint32_t array. And also pass number of bytes as last parameter which would be - sizeof(float)+sizeof(uint8_t)+sizeof(uint32_t)

提交回复
热议问题