将两个C结构打包到uint8_t指针中以写入DataFlash

时间:2018-01-30 10:54:13

标签: c pointers struct arm

我有两个C结构需要保存到DataFlash(AT45)的内存块中。我可以通过以下方式轻松保存一个这样的结构:

For One Struct

struct_name a;
struct_name * data;
data = &a;
struct_name read_buffer;

flash_write( &write_address, (uint8_t *)data, sizeof(a) ); //pack
flash_read( &read_address, (uint8_t *)read_buffer, sizeof(a) ); //unpack

包装和拆包(无填充)对于一个结构来说很容易。如果要two structs打包,我该怎么办?

For Two Struct

struct_name1 a;
struct_name2 b;
/** Pack them into one and pass reference to flash_write method */
/**    Also how do I unpack                                     */

我试图获得structstruct_name1的{​​{1}}。但对如何做到这一点很困惑。

2 个答案:

答案 0 :(得分:2)

如果两个结构都可以是数组的成员,那么它将是微不足道的:

struct_name both[2];  // both[0] is a and both[1] is b
// store data in both[0] and both[1]
...

struct_name read_buffer[2];
flash_write( &write_address, (uint8_t *)both, sizeof(both) ); //pack
flash_read( &read_address, (uint8_t *)read_buffer, sizeof(read_buffer) ); //unpack

如果它们最初不是同一个数组的成员,则可以复制它们:

struct_name both[2];
both[0] = a;
both[1] = b;

struct_name read_buffer[2];
flash_write( &write_address, (uint8_t *)both, sizeof(both) ); //pack
flash_read( &read_address, (uint8_t *)read_buffer, sizeof(read_buffer) ); //unpack

如果它们是不同的结构,只需使用结构作为聚合,如notan的答案所示。

答案 1 :(得分:2)

将两个结构打包到一个结构中并使用:

struct_name1 a;
struct_name2 b;

struct struct_for_both
{
    struct_name1 a;
    struct_name2 b;
} both = {a,b}; // initialize by copying Contents of a and b

struct_for_both read_buffer;

flash_write( &write_address, (uint8_t *)&both, sizeof(both) ); //pack
flash_read( &read_address, (uint8_t *)read_buffer, sizeof(read_buffer) ); //unpack