請考慮下面的代碼。在C中的結構指針之間施放C
typedef struct{
int field_1;
int field_2;
int field_3;
int field_4;
uint8_t* data;
uint32_t data_size;
} my_struct;
void ext_function(inalterable_my_struct* ims, ...);
我想允許ext_function
(由第三方書面)僅修改field_3
和field_4
在my_struct
。所以,我做到以下幾點:
typedef struct{
const int field_1;
const int field_2;
int field_3;
int field_4;
const uint8_t* data;
const uint32_t data_size;
} inalterable_my_struct;
void ext_function(inalterable_my_struct* ims, ...);
它是安全的主叫ext_function
(如後所示)前投my_struct
和inalterable_my_struct
之間的指針?
void call_ext_function(my_struct* ms){
inalterable_my_struct* ims = (inalterable_my_struct*)ms;
ext_function(ims, ...);
}
如果你不想'ext_function'修改'data',你應該聲明它爲'const uint8_t * const data;'' – Henrik