struct to byte[]
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Tue Dec 12 13:38:46 PST 2006
Kirk McDonald wrote:
> Luís Marques wrote:
>> Can we have a "cast(type[])" working for structures, please?
<snip>
>> E.g.
>>
>> struct Foo
>> {
>> int a;
>> float b;
>> }
>>
>> converts to ubyte[8] via "cast(ubyte[])".
>
> 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...
More information about the Digitalmars-d
mailing list