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???
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
gordonPosted Sep 20, 2007, 5:17 PM
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.
AlanPosted Sep 20, 2007, 4:46 PM
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);
gordonPosted Sep 20, 2007, 12:47 PM
AlanPosted Sep 20, 2007, 12:31 PM
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
}