在c#中将struct转换为byte []

时间:2013-09-06 19:51:22

标签: c# struct type-conversion

我在一个类中有这个结构:

[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
    public byte StartOfText;
    public byte DisableChecksum;
    public byte ProtocolVersion;
    public byte Code;
    public Int16 Size;
    public byte[] Data;
    public byte EndOfText;

    public MyStruct(CommandCode commandCode, string commandData)
    {
        this.StartOfText = 0x02;
        this.DisableChecksum = 0x00;
        this.ProtocolVersion = 0x35;
        this.Code = (byte)commandCode;
        this.Size = (Int16)commandData.Length;
        this.Data = new byte[commandData.Length];
        this.Data = Encoding.ASCII.GetBytes(commandData);
        this.EndOfText = 0x03;
    }

    public byte[] ToByteArray()
    {
        byte[] arr = null;
        IntPtr ptr = IntPtr.Zero;
        try
        {
            Int16 size = (Int16)Marshal.SizeOf(this);
            arr = new byte[size];
            ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(this, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            Marshal.FreeHGlobal(ptr);
        }

        return arr;
    }
}

现在,假设我在程序中初始化该结构的新实例,执行以下操作:

Protocol.MyStruct Cmd = new Protocol.MyStruct(CommandCode.LOAD_FILE, "TEST");
byte[] StructData = Cmd.ToByteArray();

初始化时,我可以看到正在使用字符串常量(0x54,0x45,0x53,0x54)的内容正确初始化MyStruct.Data。每个角色

但是当调用MyStruct.TiByteArray()并跟踪数组中的值时,数据部分现在是(0xa0,0xa6,0x91和0x03)。

数组的其余部分正常,数据被正确复制。

代码有什么问题,我错过了什么?

2 个答案:

答案 0 :(得分:0)

这可能在某些情况下有效。但是,数据的长度是固定的。如果将数据定义为字符串,则可能更有用。

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
    const int ARRAY_SIZE = 100;

    public byte StartOfText;
    public byte DisableChecksum;
    public byte ProtocolVersion;
    public byte Code;
    public Int16 Size;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = ARRAY_SIZE)]
    public byte[] Data;
    public byte EndOfText;

    public MyStruct(CommandCode commandCode, string commandData)
    {
        this.StartOfText = 0x02;
        this.DisableChecksum = 0x00;
        this.ProtocolVersion = 0x35;
        this.Code = (byte)commandCode;
        this.Size = (Int16)commandData.Length;
        this.Data = new byte[ARRAY_SIZE];
        byte[] bytes = Encoding.ASCII.GetBytes(commandData);
        Array.Copy(bytes, Data, bytes.Length);
        //this.Data = Encoding.ASCII.GetBytes(commandData);
        this.EndOfText = 0x03;
    }

    public byte[] ToByteArray()
    {
        byte[] arr = null;
        IntPtr ptr = IntPtr.Zero;
        try
        {
            int size = Marshal.SizeOf(this);
            arr = new byte[size];
            ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(this, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            Marshal.FreeHGlobal(ptr);
        }

        return arr;
    }
}

答案 1 :(得分:0)

在Struct声明的顶部添加SerializableAttribute并替换ToByteArray()方法,如下所示:

[StructLayout(LayoutKind.Sequential, Pack = 1), Serializable]
public struct MyStruct
{
    public byte StartOfText;
    public byte DisableChecksum;
    public byte ProtocolVersion;
    public byte Code;
    public Int16 Size;
    public byte[] Data;
    public byte EndOfText;

    public MyStruct(CommandCode commandCode, string commandData)
    {
        this.StartOfText = 0x02;
        this.DisableChecksum = 0x00;
        this.ProtocolVersion = 0x35;
        this.Code = (byte)commandCode;
        this.Size = (Int16)commandData.Length;
        this.Data = new byte[commandData.Length];
        this.Data = Encoding.ASCII.GetBytes(commandData);
        this.EndOfText = 0x03;
    }

    public byte[] ToByteArray()
    {
        BinaryFormatter formatter = null;
        MemoryStream stream = null;
        byte[] arr = null;
        try
        {
            formatter = new BinaryFormatter();
            stream = new MemoryStream();
            formatter.Serialize(stream, this);
            arr = stream.ToArray();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            if(null != stream)
            {
                stream.Dispose();
            }
        }
        return arr;
    }
}