6

使用 .NET 4.0,我可以使用 Marshal 类快速将结构与字节数组转换。例如,下面的简单示例将在我的机器上以每秒 100 万次左右的速度运行,这对于我的目的来说已经足够快了......

    [StructLayout(LayoutKind.Sequential)]
    public struct ExampleStruct
    {
        int i1;
        int i2;
    }

    public byte[] StructToBytes()
    {
        ExampleStruct inst = new ExampleStruct();

        int len = Marshal.SizeOf(inst);
        byte[] arr = new byte[len];
        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(inst, ptr, true);
        Marshal.Copy(ptr, arr, 0, len);
        Marshal.FreeHGlobal(ptr);

        return arr;
    }

但是 Marshal 类在 WinRT 下不可用,出于安全原因,这足够合理,但这意味着我需要另一种方法来实现我的结构到/从字节数组。

我正在寻找一种适用于任何固定大小结构的方法。我可以通过为每个知道如何将该特定结构转换为并形成字节数组的结构编写自定义代码来解决这个问题,但这相当乏味,我不禁觉得有一些通用的解决方案。

4

1 回答 1

2

一种方法是表达式和​​反射的组合(我将缓存作为实现细节):

// Action for a given struct that writes each field to a BinaryWriter
static Action<BinaryWriter, T> CreateWriter<T>()
{
    // TODO: cache/validate T is a "simple" struct

    var bw = Expression.Parameter(typeof(BinaryWriter), "bw");
    var obj = Expression.Parameter(typeof(T), "value");

    // I could not determine if .Net for Metro had BlockExpression or not
    // and if it does not you'll need a shim that returns a dummy value
    // to compose with addition or boolean operations
    var body = Expression.Block(
       from f in typeof(T).GetTypeInfo().DeclaredFields
       select Expression.Call(
           bw,
           "Write",
           Type.EmptyTypes, // Not a generic method
           new[] { Expression.Field(obj, f.Name) }));

    var action = Expression.Lambda<Action<BinaryWriter, T>>(
        body,
        new[] { bw, obj });

    return action.Compile();
}

像这样使用:

public static byte[] GetBytes<T>(T value)
{
    // TODO: validation and caching as necessary
    var writer = CreateWriter(value);
    var memory = new MemoryStream();
    writer(new BinaryWriter(memory), value);
    return memory.ToArray();
}

要回读这个,它会涉及更多:

static MethodInfo[] readers = typeof(BinaryReader).GetTypeInfo()
    .DeclaredMethods
    .Where(m => m.Name.StartsWith("Read") && !m.GetParameters().Any())
    .ToArray();

// Action for a given struct that reads each field from a BinaryReader
static Func<BinaryReader, T> CreateReader<T>()
{
    // TODO: cache/validate T is a "simple" struct

    var br = Expression.Parameter(typeof(BinaryReader), "br");

    var info = typeof(T).GetTypeInfo();

    var body = Expression.MemberInit(
       Expression.New(typeof(T)),
       from f in info.DeclaredFields
       select Expression.Bind(
           f,
           Expression.Call(
               br,
               readers.Single(m => m.ReturnType == f.FieldType),
               Type.EmptyTypes, // Not a generic method
               new Expression[0]));

    var function = Expression.Lambda<Func<BinaryReader, T>>(
        body,
        new[] { br });

    return function.Compile();
}
于 2011-10-07T04:29:24.803 回答