Tor Henrik Hovi Posted October 7, 2003 Posted October 7, 2003 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? Quote
AlexCode Posted October 9, 2003 Posted October 9, 2003 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 Quote Software bugs are impossible to detect by anybody except the end user.
Tor Henrik Hovi Posted October 9, 2003 Author Posted October 9, 2003 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..... Quote
AlexCode Posted October 9, 2003 Posted October 9, 2003 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 Quote Software bugs are impossible to detect by anybody except the end user.
Administrators PlausiblyDamp Posted May 22, 2007 Administrators Posted May 22, 2007 You could use serialisation do do this, simply point the serialiser to a memorystream rather than a filestream. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Leaders snarfblam Posted May 22, 2007 Leaders Posted May 22, 2007 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. Quote [sIGPIC]e[/sIGPIC]
Recommended Posts