I'm working on a library that communicated with a µController via UDP-Messages. For that I'm using a custom protocol which is basically a struct consisting of 2 elements: The header (some metadata + checksum) and the payload. The communication is done via the System.Net.Sockets.UDPClient Class. To convert my data I'm using the following function:
private List<byte> GetBytes(object str) { int size = Marshal.SizeOf(str); byte[] arr = new byte[size]; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(str, ptr, true); Marshal.Copy(ptr, arr, 0, size); Marshal.FreeHGlobal(ptr); return arr.ToList(); } I'm running into problems now if I want to send some payload which is not of a constant size, for example if I just want to write some data of variable length to the µController. One workaround that I am currently using is to just encapsulate my payload in a struct of a constant (maximum) size, but that seems not very efficient to me.
So, is there any way to convert a struct of a non constant-size to a Byte-Array with C#? For example this struct:
[StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct PERIPHERY__PROTOCOL { public PERIPHERY_HEADER strHeader; public byte[] Data; }