How to safely convert unsigned integral value (e.g. uint32_t
, uint64_t
) to a pointer of particular type?
For instance I have:
using my_uint32_t = unsigned int;
using my_uint64_t = unsigned long long;
struct Sample {
my_uint32_t address;
my_uint64_t address_64;
};
Sample sample; /* Just for reference here */
struct TargetStruct {
/* Some member variables goes here */
...
};
The goal is to access the object of TargetStruct
type existing at Sample.address
or Sample.address64
respectively.
I tried to use:
TargetStruct * target = reinterpret_cast<TargetStruct *>( sample );
It works but is that safe? I know the rules say reinterpret_cast
shall be avoided as unsafe but is there any other way to make it safely?
I cannot go over my "inputs" - the Sample
struct and it's content - it is simply given but I have to use the data stored in there in such usafe way...
I am using C++20 so I am about to avoid C-style casts...