c# - 使用 MemoryMappedViewAccessor 错误编写打包结构?

标签 c# struct marshalling memory-mapped-files

我有一个用 Pack=1 定义的结构,它有 29 个字节长。如果它没有打包,它将是 32 个字节长。

  • Marshal.SizeOf(TypeOf(StructName)) 返回 29。

  • 结构名称结构; sizeof(struct) 返回 32。

当我使用 MemoryMappedViewAccessor 写出该结构时,它写出 32 个字节,而不是 29 个字节。

那么,除了将结构编码为字节数组并以这种方式写出来之外,还有什么方法可以让它正确地写出该结构吗?

更多细节:如果您使用显式布局,Write 实际上会写出 29 个字节。但是,WriteArray 为每个元素写出 32 个字节。

avip,是的,细致的字节序列化可能会起作用,但是(我没有分析它,但我猜)它可能比 WriteArray 慢几个数量级,不?

最佳答案

编辑:好的,我终于明白你真正在问什么了。我们通常不使用 MemoryMappedViewAccessor 来序列化对象,现在你知道为什么了。

下面会给你预期的结果。

public static class ByteSerializer
{
    public static Byte[] Serialize<T>(IEnumerable<T> msg) where T : struct
    {
        List<byte> res = new List<byte>();
        foreach (var s in msg)
        {
            res.AddRange(Serialize(s));
        }
        return res.ToArray();
    }

    public static Byte[] Serialize<T>(T msg) where T : struct
    {
        int objsize = Marshal.SizeOf(typeof(T));
        Byte[] ret = new Byte[objsize];

        IntPtr buff = Marshal.AllocHGlobal(objsize);
        Marshal.StructureToPtr(msg, buff, true);
        Marshal.Copy(buff, ret, 0, objsize);
        Marshal.FreeHGlobal(buff);
        return ret;
    }
}

class Program
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    struct Yours
    {
        public Int64 int1;
        public DateTime dt1;
        public float f1;
        public float f2;
        public float f3;
        public byte b;
    }

    static void Main()
    {
        var file = @"c:\temp\test.bin";
        IEnumerable<Yours> t = new Yours[3];
        File.WriteAllBytes(file, ByteSerializer.Serialize(t));

        using (var stream = File.OpenRead(file))
        {
            Console.WriteLine("file size: " + stream.Length);
        }
    }
}

编辑:看来 DateTime 确实喜欢位于对齐的内存地址上。虽然您可以定义显式布局,但我认为更简单的方法是:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Test
{
    private long dt1; 
    public byte b;
    public Int64 int1;
    public float f1;
    public float f2;
    public float f3;

    public DateTime DT
    {
        get { return new DateTime(dt1); }
        set { dt1 = value.Ticks; }
    }
}

虽然我不明白为什么你应该关心托管内存表示。

或者,[StructLayout(LayoutKind.Explicit)] 应该防止内存对齐。

示例('managed sizeof' 取自 this post )

[StructLayout(LayoutKind.Explicit, Size = 9)]
public struct Test
{
    [FieldOffset(0)]
    public DateTime dt1;
    [FieldOffset(8)]
    public byte b;
}

class Program
{
    static readonly Func<Type, uint> SizeOfType = (Func<Type, uint>)Delegate.CreateDelegate(typeof(Func<Type, uint>), typeof(Marshal).GetMethod("SizeOfType", BindingFlags.NonPublic | BindingFlags.Static));

    static void Main()
    {
        Test t = new Test() { dt1 = DateTime.MaxValue, b = 42 };
        Console.WriteLine("Managed size: " + SizeOfType(typeof(Test)));
        Console.WriteLine("Unmanaged size: " + Marshal.SizeOf(t));
        using (MemoryMappedFile file = MemoryMappedFile.CreateNew(null, 1))
        using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
        {
            accessor.Write(0L, ref t);
            long pos = 0;

            for (int i = 0; i < 9; i++)
                Console.Write("|" + accessor.ReadByte(pos++));
            Console.Write("|\n");
        }
    }
}

输出:

Managed size: 9
Unmanaged size: 9
|255|63|55|244|117|40|202|43|42|   // managed memory layout is as expected

顺便说一句,DateTime 似乎打破了顺序契约——但请记住契约是针对 Marshaled 内存映射的。没有关于托管内存布局的规范。

[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 9)]
public struct Test
{
    public DateTime dt1;
    public byte b;
}

以上代码的输出:

Managed size: 12
Unmanaged size: 9
|42|0|0|0|255|63|55|244|117|40|202|43|   // finally found those 3 missing bytes :-)

关于c# - 使用 MemoryMappedViewAccessor 错误编写打包结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13319351/

相关文章:

c# - 如何在控制台中使用空格分隔多个输入

c# - 在 WPF MVVM 中绑定(bind)图像

arrays - 配置单元 : ParseException line 3:23 cannot recognize input near 'from'

java - 将大型 XML 文件转换为 java 对象?

java - 使用 JAXB 编码(marshal)时出现内存不足错误

c# - TimeSpan.ToString() 上的 System.FormatException

c# - 删除文件前几个字节的最快方法

php - Python 包到 PHP 包

c++ - 如何遍历具有结构指针的 vector ?

c# - 位图到 int[] 使用 Marshal.Copy()