Converting a structure to a byte array
Is there a method or way of converting a structure to a byte array in one step. Or is there a way of transmitting data on the network without converting to a byte array???
4 Answers
Know the answer? Post it. Somebody with the same question will find it here.

AlanRank #669 · 3.6K reputationPosted Sep 20, 2007, 8:31 AM EDT
Well, you could do it in a few lines with this code:
using System.Runtime.InteropServices;
.......
SomeStruct ss = new SomeStruct();
int size = Marshal.SizeOf(ss);
byte[] ba = new byte[size];
IntPtr ip = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(ss, ip, true);
Marshal.Copy(ip, ba, 0, size);
Marshal.FreeHGlobal(ip);
However, for this to work properly, you need to mark your struct definition with the following attribute:
[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
// code
}
gordon47 reputationPosted Sep 20, 2007, 8:47 AM EDT
AlanRank #669 · 3.6K reputationPosted Sep 20, 2007, 12:46 PM EDT
No, it's not exactly obvious :)
Incidentally, Gordon, if you need to unpack the byte array into a struct following transmission, then this code should do it (same variables as before):
ip = Marshal.AllocHGlobal(size);
Marshal.Copy(ba, 0, ip, size);
ss = (SomeStruct)Marshal.PtrToStructure(ip, typeof(SomeStruct));
Marshal.FreeHGlobal(ip);
gordon47 reputationPosted Sep 20, 2007, 1:17 PM EDT
Thanks Alan works fine.
In the structure I did need to use the Pack =1 attribute as for unpacking it's going to a program written in C++ but thanks for the info.