3 ms·
> These two macros now let you safely create unaligned pointers. So now the compiler will generate calls to memcpy() for accesses to unaligned elements in pack
by wyldfire 6y ago
> These two macros now let you safely create unaligned pointers.
So now the compiler will generate calls to memcpy() for accesses to unaligned elements in packed structures like the one in the example?
- kzrdude 6y agoGood question. I think the answer is no, and that `let value = *ptr;` is UB if the pointer is misaligned. The right way to go is `let value = ptr.read_unaligned();` But the docs will say this: > Accessing unaligned fields directly with e.g. packed.unaligned is safe however. https://doc.rust-lang.org/nightly/std/ptr/fn.read_unaligned.html https://doc.rust-lang.org/nightly/std/ptr/fn.read_unaligned....
- coolreader18 6y agoCreating unaligned references is UB, so it's illegal to take a reference to a packed struct field. However, even if you just wanted to create a raw pointer to that field, you would've had to do `&packed.f2 as *const u16`, which is technically UB since you do create a temporary reference before casting it to a pointer. I'm sure one way to solve that is to just allow that as a special case; say that `&<expr> as *const _` semantically doesn't actually create a reference. But, the way the lang team went is to have a separate macro that transforms `ptr::addr_of!(<expr>)` to something like C's `&<expr>` operator, so that it creates a raw pointer directly instead of a reference.
- kzrdude 6y agoMaking the existing syntax - `&<expr> as *const _` like you said - just work would be far and away the best solution. Otherwise we have a 5-year transition period before all code out there that touch this get the memo.