struct to byte[]

John Demme me at teqdruid.com
Tue Dec 12 20:41:39 PST 2006


Luís Marques wrote:

> Frits van Bommel wrote:
>> Kirk McDonald wrote:
>>> Foo f;
>>> ubyte[] u = (cast(ubyte*)&f)[0 .. Foo.sizeof];
>> 
>> Or:
>> 
>> Foo f;
>> ubyte[] u = cast(ubyte[])(&f[0..1]);
>> 
>> This works more cleanly with types of size > 1 as well, but IIRC
>> basically asserts[1] (Foo.sizeof % T.sizeof == 0). So don't use this
>> code if you're not sure it will fit exactly into a T[].
>> 
>> 
>> [1]: Statically? Don't recall at the moment...
> 
> I have been using Kirk's version. Frits' variant is interesting
> (thanks!). Still, is there a reason not to allow a direct cast to
> ubyte[]? I don't see much of a problem and I suppose it wouldn't be much
> work (no?). It seems so much cleaner and readable to just cast it
> directly.

The reason Foo cannot be casted to ubyte is because they are different
sizes.  ubyte[] is a pointer and a length, whereas Foo is anything.  It
makes more sense to be able to be able to cast from a Foo* to ubyte, thus
the & in Kirk's code.  This, however, will only fill the pointer part of
ubyte[]- it still can't know the length.  The [0 .. Foo.sizeof] bit gives
the dynamic array the length.

If you're looking for an operator to convert a arbitrary piece of data to an
array of bytes, a cast is not what you're looking for.  I agree this would
be useful, though... A template in phobos would be nice.

-- 
~John Demme
me at teqdruid.com
http://www.teqdruid.com/



More information about the Digitalmars-d mailing list