I have a structure as shown below
[StructLayout(LayoutKind.Sequential)] public struct MyStructType { [MarshalAs(UnmanagedType.U1)] public byte stx; public UInt16 cmdId; public UInt16 status; public UInt16 pktNo; [MarshalAs(UnmanagedType.U1)] public byte contPkt; [MarshalAs(UnmanagedType.U1)] public byte dataoffset; public UInt16 dataLength; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] public byte[] data; public UInt16 checkSum; [MarshalAs(UnmanagedType.U1)] public byte cr; }
I tried to convert this structure to an array of bytes using the code below.
byte[] ConvertStructureToByteArray(MyStructType 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; }
but I got an error below because the size they do not know
The type "MyStructType" cannot be marshaled as an unmanaged structure; no significant size or bias.
problem due
public UInt16 dataLength; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] public byte[] data;
dataLength is computed at runtime. How to convert this structure to ByteArray?
source share