在c#中将类序列化为字节数组

时间:2013-11-26 16:00:38

标签: c# arrays serialization

我正在为我的类编写自定义序列化程序,它应该将类对象序列化为字节数组。以下是我的示例代码:

[StructLayout(LayoutKind.Sequential)]
public class ATTRIBUTE_STR
{
    public uint atType;
    public uint atLen;
    public byte[] atData = new byte[3];

    public byte[] serialize()
    {
        byte[] temp = new byte[Marshal.SizeOf(this)];

        byte[] buffer = BitConverter.GetBytes(atType);
        Array.Copy(buffer, 0, temp, 0, buffer.Length);

        buffer = null;
        buffer = BitConverter.GetBytes(atLen);
        Array.Copy(buffer, 0, temp, 4, buffer.Length);

        Array.Copy(this.atData, 0, temp, 8, this.atData.Length);

        return temp;

    }

};

然而,字节数组atData因为它如何以字节对齐方式存储在内存中,所以它没有正确地进入临时字节数组。由于字节数组具有偶数字节对齐。

如何序列化此对象以解释内存中成员的对齐?

编辑:我知道还有其他选项,如编组或ProtocolBuffers,但我想使用我的自定义序列化器。

1 个答案:

答案 0 :(得分:1)

你的大小调用可能没有返回你认为的那个,但是如果你要坚持使用硬编码的输出偏移,那么对于Sizeof几乎没有什么担心。]

所以你不妨做这样的事情:

byte[] temp = new byte[8+atLen.Length];
BitConverter.GetBytes(atType).CopyTo(temp,0);
BitConverter.GetBytes(atLen).CopyTo(temp,4);
this.AtData.CopyTo(temp,8);
return temp;

更新:Sizeof返回存储对象所需的非托管空间量 - 但请记住,您的atData数组内容未存储在对象中,它们位于对象引用的数组对象中。所以Marshal.Sizeof不会给你一个包含数组大小的答案 - 事实上,如果你让Marshal.Sizeof给你一个Sizeof(atData),你就会得到一个例外。

相关问题