C# 结构体转字节数组

(1)定义结构体

    public struct Data1
    {
        [MarshalAs(UnmanagedType.ByValArray)]
        public char[] Device_ID;     //size of 2

        [MarshalAs(UnmanagedType.ByValArray)]
        public char[] Message_ID;    //size of 3

        public char Content_ID;
        public short Message_LH;
    }

(2)结构体赋值

  Data1 data = new Data1();
  data.Device_ID = new char[2];
  data.Message_ID = new char[3];
  data.Message_ID[0] = 'M';
  data.Message_ID[1] = 'A';
  data.Message_ID[2] = 'C';
  data.Content_ID = '1';
  data.Device_ID[0] = 'D';
  data.Device_ID[1] = 'M';
  data.Message_LH =7;

(3)结构体转为byte数组函数

  public byte[] StructToBytes(T obj)
        {
            int size = Marshal.SizeOf(typeof(T));
            IntPtr bufferPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(obj, bufferPtr, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(bufferPtr, bytes, 0, size);
                return bytes;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in StructToBytes ! " + ex.Message);
            }
            finally
            {
                Marshal.FreeHGlobal(bufferPtr);
            }
        }

(4)函数调用

byte[] Data = StructToBytes(data);

你可能感兴趣的:(windows,开发语言,c#)