struct to byte[]
Luís Marques
luismarques+spam at gmail.com
Thu Dec 14 02:01:57 PST 2006
Derek Parnell wrote:
> Yes, but unfortunately the actual function is faulty. Here is what I had to
> do to get it to work ...
>
> ubyte [] toByteArray (T) (inout T t)
> {
> union ubyte_abi
> {
> ubyte[] x;
> struct
> {
> uint xl; // length
> void* xp; // ptr
> }
> }
> ubyte_abi res;
> res.xp = cast(void*)&t;
> res.xl = T.sizeof;
> return res.x;
> }
>
> unittest
> {
> struct Foo_uni
> {
> int a;
> real b;
> char[4] c;
> dchar[] d;
> }
> Foo_uni f;
> ubyte[] b;
>
> b = toByteArray(f);
>
> assert(b.length == f.sizeof);
> assert(cast(void*)(b.ptr) == cast(void *)&f);
>
> real c;
> b = toByteArray(c);
> assert(b.length == c.sizeof);
> assert(cast(void*)(b.ptr) == cast(void *)&c);
>
> class Bar_uni
> {
> int a;
> real b;
> char[4] c;
> dchar[] d;
> }
> Bar_uni g = new Bar_uni;
>
> b = toByteArray(g.d);
> assert(b.length == g.d.sizeof);
> assert(cast(void*)(b.ptr) == cast(void *)&g.d);
>
> }
Amazing. Thanks.
Yet, by this time, don't you think it would be best if the compiler
worked out the cast to ubyte[] on its own?
More information about the Digitalmars-d
mailing list