proposal: add bytesof Property, reduce pointer/cast requires
redsea
redsea at 163.com
Sat Nov 17 20:33:30 PST 2007
This help some, but it don't work at static array, and literal integer, read following, the first call is ok, next 2 call is not ok, change ref to in cause other problems, still not ok. (d 1.022)
module test;
import tango.io.Stdout;
alias Stdout od;
byte[] bytesof(T)(ref T t)
{
return (cast(byte*)&t)[0 .. t.sizeof];
}
struct SS
{
int a;
int b;
}
int main()
{
SS [10] as;
SS s;
od(bytesof(s).length).newline;
od(bytesof(as).length).newline;
od(bytesof(3).length).newline;
return 0;
}
Jarrett Billingsley Wrote:
> "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