Casting pointers
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 27 06:32:16 PDT 2015
On 8/26/15 8:14 AM, John Burton wrote:
> This would be undefined behavior in c++ due to aliasing rules on
> pointers. It appears to "work" reliably in D when I try it, but that's
> obviously no guarantee that it's correct or will continue to do so.
>
> Is this correct code in D? And if not, what should I do instead to
> cleanly and efficiently extract structured data from a sequence of bytes?
>
> import std.stdio;
>
> struct data
> {
> int a;
> int b;
> }
>
> void main()
> {
> byte[] x = [1, 2, 3, 4, 5, 6, 7, 8];
>
> data* ptr = cast(data*)(x);
> printf("%x %x\n", ptr.a, ptr.b);
>
> }
This should be defined behavior (but there is an issue that will
probably eventually be fixed -- you shouldn't cast an array to a
pointer, use x.ptr instead). I think strict aliasing only comes into
play when something is *changed*. For example:
byte[] x = [1, 2, 3, 4, 5, 6, 7, 8];
data* ptr = cast(data *)(x.ptr);
ptr.a = 4;
writefln("%x %x\n", x[0], x[1]);
However, if we consider the strict aliasing rule from C++ allows casting
to char * and unsigned char *, D's byte[] and ubyte[] should be
equivalent to those. So if anything, that should be defined.
-Steve
More information about the Digitalmars-d-learn
mailing list