You may also try code like the following if what you actually want is to transfer structures as a byte array:
int rawsize = Marshal.SizeOf(value);
byte[] rawdata = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);
Marshal.StructureToPtr(value, handle.AddrOfPinnedObject(), false);
handle.Free();
This converts the given object value to the byte array rawdata. I've taken this from code I previously wrote, and you may need to adapt it to your needs to make it actually work. I used it for communication with some hardware with user-defined structures, but it should work for built-in types as well (after all, they're structures, aren't they?)
To make structure members properly aligned, use the StructLayout attribute to specify one-byte-alignment:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
And then use the MarshalAs attribute as needed for fields, e.g. for inline arrays:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
byte[] _state;
The code to get the structure back from the byte array is something like this:
public T GetValue<T>()
{
GCHandle handle = GCHandle.Alloc(RawValue, GCHandleType.Pinned);
T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),
typeof(T));
handle.Free();
return structure;
}
Of course you'll need to know the type you want for this to work.
Note that this will not handle endianness for itself. In my project, most fields were one byte only, so it didn't matter, but for the few fields where it did, I just made the fields private and added public properties that would take care of the endianness (Jon Skeet's link from a comment to his answer may help you, I wrote some utility functions for this since I needed only few).
When I needed this, I created a Message class that would store the raw value (hence the GetValue method, the code at the top is actually the body of a SetValue method) and had some nice convenience method to get the value formatted etc.