struct to byte[]

Derek Parnell derek at nomail.afraid.org
Thu Dec 14 17:08:04 PST 2006


On Thu, 14 Dec 2006 18:10:56 +0000 (UTC), BCS wrote:

> == Quote from Derek Parnell (derek at nomail.afraid.org)'s article
>> With this, the '&t' phrase takes the address of the data as
>> passed-by-value. [...] So you end up with a ubyte[]
>> array that references a copy of the struct/data you supplied
>> [...] Of course, that might be what you are trying to do ;-)
> 
> I get it now! The kind of things I would use it for would only care about the copy
> from a performace standpoint.
> 
> OTOH: would this work?
> 
> ubyte [] toByteArray (T) (inout T t)
> {
>    return (cast(ubyte *)&t)[0..T.sizeof].dup
> }

LOL ... That is just *so* much better than my complex method. If you remove
the '.dup', which gets the exact effect of my routine, your generated
machine code is very optimized. 

Your version:
	mov	EDX,EAX
	mov	EAX,01Ch
	ret


My version:
	enter	8,0
	push	EBX
	mov	EDX,__init...ubyte_abi[04h]
	mov	EBX,__init...ubyte_abi
	mov	-8[EBP],EBX
	mov	-4[EBP],EDX
	mov	-4[EBP],EAX
	mov	dword ptr -8[EBP],01Ch
	mov	EDX,-4[EBP]
	mov	EAX,-8[EBP]
	pop	EBX
	leave
	ret

So I'll stick to this now ...

 ubyte [] toByteArray (T) (inout T t)
 {
    return (cast(ubyte *)&t)[0..T.sizeof];
 }

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
15/12/2006 12:00:30 PM



More information about the Digitalmars-d mailing list