Casting arrays
Dennis
dkorpel at gmail.com
Thu May 30 08:30:14 UTC 2019
On Thursday, 30 May 2019 at 01:14:57 UTC, solidstate1991 wrote:
> /**
> * Safely casts one type of an array to another.
> */
> T[] reinterpretCast(T, U)(ref U[] input) @trusted{
> T[] _reinterpretCast() @system{
> return cast(T[])(cast(void[])input);
> }
> if ((U.sizeof * input.length) % T.sizeof == 0){
> return _reinterpretCast();
> } else {
> throw new Exception("Cannot cast safely!");
> }
> }
Don't do this, that function can not be trusted. For casts of
basic types, the compiler already has such runtime checks:
```
int[] a = [3, 4, 5];
auto b = cast(double[]) a;
```
"An array of size 12 does not align on an array of size 8, so
`int` cannot be cast to `double`"
You allowing it for ANY type as long as alignment is okay invites
all kinds of safety violations.
```
void main() @safe
{
char*[1] a = [new char('\xCC')];
auto slice = a[];
auto b = reinterpretCast!(int*)(slice);
writefln("%08X", *b[0]);
}
```
https://run.dlang.io/is/QVNlEv
Prints:
743B50CC
The 74 3B 50 are bytes out of bounds. There's more to array
casting than alignment for it to be safe.
More information about the Digitalmars-d
mailing list