Cast between struct pointer in C
c, casting
Solution
I don't think this is a good idea.
The called function can always cast away any `const`:ness, and modify the data if it wants to.
If you can control the callpoints, it would be better to create a copy and call the function with a pointer to the copy, then copy back the two fields you care about:
void call_ext_function(my_struct* ms)
{
my_struct tmp = *ms;
ext_function(&tmp, ...);
ms->field_3 = tmp.field_3;
ms->field_4 = tmp.field_4;
}
much cleaner, and unless you do this thousands of times a second the performance penalty should really be minor.
You might have to fake the pointer-based data too, if the function touches it.
Problem
Please consider the following code. ``` 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, ...); ``` I want to allow `ext_function` (written by a third party) to modify only `field_3`and `field_4` in `my_struct`. So I do the following: ``` 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, ...); ``` Is it safe to cast pointers between `my_struct` and `inalterable_my_struct` before calling `ext_function` (as shown after)? ``` void call_ext_function(my_struct* ms){ inalterable_my_struct* ims = (inalterable_my_struct*)ms; ext_function(ims, ...); } ```