Casting arrays

solidstate1991 laszloszeremi at outlook.com
Thu May 30 01:14:57 UTC 2019


For casting arrays in @safe functions between very different 
types, I have to write a @trusted wrapper that checks if the two 
arrays are within boundaries, then returns the requested array 
type (or even a single instance with a different one) from the 
nested @system function, and throws an exception if the cast 
would result in an error.

Here's an example of one such wrapper, I probably have to put 
them into a separate library instead:

/**
  * 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!");
	}
}

The cast to void[] is needed because D often doesn't always let 
me to cast directly between types this way ("Cannot implicitly 
cast between types..."), especially structs.


More information about the Digitalmars-d mailing list