编辑:好的,我终于明白你真正想问什么了。我们通常不使用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)]
应该可以防止内存对齐。
例如('托管 sizeof' 取自这篇文章)
[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似乎破坏了连续性协议 - 但请记住,该协议仅适用于内存映射。对于托管内存布局,没有任何规范。
[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 :-)
Marshal.AlignedSizeOf<T>()
,而不考虑打包。 - Hans Passant