On Sun, Jun 04, 2017 at 06:12:42PM -0700, H. S. Teoh wrote:
> On Mon, Jun 05, 2017 at 01:14:31AM +0000, Mike B Johnson via 
> Digitalmars-d-learn wrote:
> [...]
> > Guid is a struct and I am trying to get the "bytes" of the struct" to
> > get the guid bytes. It is quicker than accessing all the elements one
> > at a time.
> 
>       union U {
>               typeof(guid) guid;
>               ubyte[guid.sizeof] bytes;
>       }
>       U u;
>       u.guid = guid;
>       // ... do something with u.bytes.
[...]

And if you're going to be doing this a lot on many different types, you
could ease the typing by declaring a template for it, for example:

        union AsBytes(T) {
                T t;
                ubyte[T.sizeof] bytes;
        }
        ubyte[T.sizeof] asBytes(T)(T t) {
                AsBytes!T u;
                u.t = t;
                return u.bytes;
        }
        ...
        struct S {
                /* stuff */
        }

        S s;
        auto bytes = s.asBytes;
        ... /* do stuff with bytes, which is a static array of ubyte */

Note, of course, that this will be @system if T contains any pointers.


T

-- 
2+2=4. 2*2=4. 2^2=4. Therefore, +, *, and ^ are the same operation.

Reply via email to