Size of managed structures

前端 未结 3 731
野趣味
野趣味 2020-12-09 05:47

The .NET 4.0 Framework introduces classes for reading and writing memory mapped files. The classes are centred around methods for reading and writing structures. These are n

3条回答
  •  抹茶落季
    2020-12-09 06:23

    It seems there is no documented/public way to access the internal SizeOfType function used by the MemoryMappedViewAccessor class, so the most practical way of getting the size of those structures would be to use reflection like this:

    static readonly Func SizeOfType = (Func)Delegate.CreateDelegate(typeof(Func), typeof(Marshal).GetMethod("SizeOfType", BindingFlags.NonPublic | BindingFlags.Static));
    
    static void Write(T1 item1, T2 item2)
        where T1 : struct
        where T2 : struct
    {
        using (MemoryMappedFile file = MemoryMappedFile.CreateNew(null, 32))
        using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
        {
            accessor.Write(0, ref item1);
            accessor.Write(SizeOfType(typeof(T1)), ref item2);
        }
    }
    

提交回复
热议问题