Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi guys!

I have a structure like this:

 

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?

Posted

Sorry but I didn't 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

Software bugs are impossible to detect by anybody except the end user.
Posted

OK, first of all thanx for taking the time to look into my problem.

:D

Let's say did something like this:

 

       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.

 

I'm perhaps not very good at explaining my problem.....

Posted

As long as I know there's no built-in method that does that...

 

You'll have to do it by hand...

It doesn't seem to be that hard too! :D

Software bugs are impossible to detect by anybody except the end user.
  • 3 years later...
  • Leaders
Posted

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 haven't tested it) and the binary result may or may not be the same as that of the binary serializer (I'm 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.

[sIGPIC]e[/sIGPIC]
Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...