struct to byte[]

Gregor Richards Richards at codu.org
Tue Dec 12 14:48:26 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.

I agree. There are plenty of ways to cast it, but they're fairly arcane. 
This is useful enough, and so long as it's explicit I don't think it's 
at all confusing.

Perhaps as an alternative (idea stolen from #d), some_struct.bytearray 
as an implicit property.

  - Gregor Richards



More information about the Digitalmars-d mailing list