proposal: add bytesof Property, reduce pointer/cast requires

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Nov 17 18:33:56 PST 2007


"redsea" <redsea at 163.com> wrote in message 
news:fho4go$1r6t$1 at digitalmars.com...
>I found D's array and slice is very useful, most time I can use byte [] to 
>finish my work without using pointer.
>
> But when I need to copy from/to a struct I need to use code like this:
>
> byteary[i..i+structvar.sizeof] = (cast (byte 
> *)&structvar)[0..structvar.sizeof)
>
> the cast, the &, looking bad, and code is complex.
>
> if d can supply a internal property, let's say bytes of, can give us the 
> correctly byte [] slice, then I can write:
>
> byteary[i..i+struct.var.sizeof] = structvar.bytesof
>
> and, when we write a function send struct to network, we can simple write:
> void sendPacket(byte[] content);
>
> and we can use as that:
>
> sendPacket(structvar.bytesof);
>
> any suggestions ?
>

byte[] bytesOf(T)(ref T t)
{
    return (cast(byte*)&t)[0 .. t.sizeof];
}

byteArray[i .. i + struct.var.sizeof] = bytesOf(structVar);
sendPacket(bytesOf(structVar)); 





More information about the Digitalmars-d mailing list