struct to byte[]

Derek Parnell derek at nomail.afraid.org
Wed Dec 13 15:47:09 PST 2006


On Wed, 13 Dec 2006 14:22:32 -0600, Chris Nicholson-Sauls wrote:

> Endea wrote:
>> novice2 kirjoitti:
>>> == Quote from Alexander Panek (a.panek at brainsware.org)'s article
>>>> ubyte [] toByteArray (T) (T t) {
>>>>     return (cast(ubyte *)&t)[0..T.sizeof].dup
>>>> }
>>>
>>>> auto b = toByteArray!(Foo)(f); // Yay!
>>>
>>> why we need two parameters?
>>> compiler don't know type of f?
>> 
>> This works:
>> 
>> auto b = toByteArray(f); // Yay!
> 
> Huzzah for IFTI!

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);

}


-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
14/12/2006 10:45:46 AM



More information about the Digitalmars-d mailing list