Structure to Array of bytes

Joined
Mar 3, 2003
Messages
9
Location
Norway
Hi guys!
I have a structure like this:

Code:
Public Structure SendBuffer
        Public MagicCookie As Short
        Public Command As Short
        Public Length As Integer
        Public Data As Byte()
    End Structure

and I would like to convert it to a 1-dimensional array of bytes.

is there a fancy and swift way of doing this or do I have to do it manually?
 
Sorry but I didnt got it...

Give me an example of the data on this structure now as it is and as you wish it to be on the array of bytes ok?

:D
 
OK, first of all thanx for taking the time to look into my problem.
:D
Lets say did something like this:

Code:
        Dim TempStruct As SendBuffer
        TempStruct.MagicCookie = &HABBA
        TempStruct.Command = 1
        TempStruct.Length = 8
        TempStruct.Data = Nothing

I would then somhow like to get the structure as an array of bytes:
(171,186,0,1,0,0,0,8)

Much as if i pointed an array to the same place as Tempstruct in memory.

Im perhaps not very good at explaining my problem.....
 
As long as I know theres no built-in method that does that...

Youll have to do it by hand...
It doesnt seem to be that hard too! :D
 
I would go with a binary serializer, like PD said, but just to throw this out there, there is always the option of using the Marshal class to do this. It might be quicker (or it could be slower, I havent tested it) and the binary result may or may not be the same as that of the binary serializer (Im not sure if they both align data the same way). Basically, you could use Marshal.SizeOf to get the number of bytes in the structure in packed form (no padding for 32-bit alignment). Then you could use Marshal.AllocHGlobal to allocate memory, Marhsal.StructureToPtr to copy the structure to that memory, Marshal.Copy to move that into a byte array, and Marshal.FreeHGlobal to release the memory that you allocated (the memory can be re-used as many times as you like before you free it).

Now, this has about a 1% chance of benefitting your project, but its fun to get your hands dirty with binary and you will learn some of the things you can do with the marshal class. Of course, if this seems a bit over the top or confusing, by all means, ignore my post.
 
Back
Top