struct to byte[]
Hasan Aljudy
hasan.aljudy at gmail.com
Wed Dec 13 23:28:15 PST 2006
Derek Parnell wrote:
> On Wed, 13 Dec 2006 20:48:43 -0800, BCS wrote:
>
>> Derek Parnell wrote:
>>> 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;
>>> }
>>>
>> What didn't work???
>> Unless arrays are broken, that should be the same.;
>
> The original function was
>
> ubyte [] toByteArray (T) (T t)
> {
> return (cast(ubyte *)&t)[0..T.sizeof].dup
> }
>
> With this, the '&t' phrase takes the address of the data as
> passed-by-value. Which means that when passing a struct or basic type, you
> get the address of the copy of the data which of course is not in scope
> when you return from the function. The '.dup' takes another copy of the
> data (this time on the heap) and you return the ubyte[] reference to the
> second copy. So you end up with a ubyte[] array that references a copy of
> the struct/data you supplied to the function and doesn't reference the
> initial data at all. Of course, that might be what you are trying to do ;-)
> I just thought that what was being attempted was to have a ubyte[] to
> access the data in the original struct instance and not a copy of it.
>
>
> My function avoids taking copies of the data and returns a ubyte[]
> reference to the actual struct/data instance passed to the function.
>
> Both are invoked with identical syntax thanks to IFTI and D's handling of
> inout parameters.
>
But why did you need the union/struct trick?
And with this, isn't the compiler free to rearrangre struct fields??
union ubyte_abi
{
ubyte[] x;
struct //isn't the compiler free to rearrangre struct fields??
{
uint xl; // length
void* xp; // ptr
}
}
More information about the Digitalmars-d
mailing list