我有一个像下面这样的结构
[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; }
我试图通过使用下面的代码将此结构转换为字节数组.
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; }
但我得到了以下错误,因为他们不知道的大小
类型'MyStructType'不能作为非托管结构封送; 不能计算有意义的大小或偏移量.
因为这个问题
public UInt16 dataLength; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] public byte[] data;
dataLength根据运行时计算.如何将此结构转换为ByteArray?