管理结构的大小 [英] Size of managed structures

查看:72
本文介绍了管理结构的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET 4.0框架引入了类<一href="http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile%28VS.100%29.aspx">reading和写入内存映射文件。该课程是围绕为阅读和的writing结构的。这些都不是整理,但复制的,并在它们在托管内存布局形式的文件。

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 not marshalled but copied from and to the file in the form in which they are laid out in managed memory.

比方说,我想用这些方法来写两个结构依次为内存映射文件:

Let's say I want to write two structures sequentially to a memory mapped file using these methods:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Foo
{
    public char C;
    public bool B;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Bar
{
}

static void Write<T1, T2>(T1 item1, T2 item2)
    where T1 : struct
    where T2 : struct
{
    using (MemoryMappedFile file = MemoryMappedFile.CreateNew(null, 32))
    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
    {
        accessor.Write<T1>(0L, ref item1);  //  <-- (1)
        accessor.Write<T2>(??, ref item2);  //  <-- (2)
    }
}

static void Main()
{
    Foo foo = new Foo { C = 'α', B = true };
    Bar bar = new Bar { };
    Write(foo, bar);
}

我该如何获得写入的字节数(1),所以我可以写相邻的下一个值(2)?

How would I get the number of bytes written in (1) so I can write the next value adjacently in (2)?

注意:字节示例中的数目是3(= 2 + 1),而不是图5(= 1 + 4)所返回Marshal.SizeOf

注2:的sizeof 不能确定的泛型类型参数的大小

Note 2: sizeof cannot determine the size of generic type parameters.

推荐答案

这似乎是没有记录/公开的方式来访问所用的<$内部 SizeOfType 功能C $ C> MemoryMappedViewAccessor ​​类,因此让这些结构的大小的最实用的方法是使用反射像这样的:

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<Type, uint> SizeOfType = (Func<Type, uint>)Delegate.CreateDelegate(typeof(Func<Type, uint>), typeof(Marshal).GetMethod("SizeOfType", BindingFlags.NonPublic | BindingFlags.Static));

static void Write<T1, T2>(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);
    }
}

这篇关于管理结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆