First Draft: cast(ref T)... as shorthand for *cast(T*)&...
Paul Backus
snarwin at gmail.com
Tue Feb 25 17:06:31 UTC 2025
On Tuesday, 25 February 2025 at 12:46:53 UTC, Dukc wrote:
> If anything, we want a library helper function like Paul
> suggested, but I'm slightly reserved even about that. When
> doing reinterpret casts, it's extremely important to understand
> exactly how the cast works. Any abstraction over that always
> tends to more or less hide it.
IMO `reinterpretCast!T` is actually more explicit about what's
going on than `*cast(T*) &`.
The pointer used in these casts is a language-level abstraction
that doesn't actually exist at runtime. If you look at the
generated assembly, it's just a `mov` instruction.
For example, this code:
ulong doubleAsInt(double num)
{
return *cast(ulong*) #
}
size_t ptrAsSize(void* p)
{
return *cast(size_t*) &p;
}
...produces the following assembly:
ulong example.doubleAsInt(double):
push rbp
mov rbp, rsp
movsd qword ptr [rbp - 8], xmm0
mov rax, qword ptr [rbp - 8] ; *cast(ulong*) &num
pop rbp
ret
ulong example.ptrAsSize(void*):
push rbp
mov rbp, rsp
mov qword ptr [rbp - 8], rdi
mov rax, qword ptr [rbp - 8] ; *cast(size_t*) &p
pop rbp
ret
Godbolt link: https://d.godbolt.org/z/xGGKnPrWs
More information about the dip.development
mailing list