使用.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下是不可用的,出于安全原因这是合理的,但这意味着我需要另一种方法来实现我的结构到/从字节数组。
我正在寻找适用于任何固定大小结构的方法。我可以通过为每个知道如何将特定结构转换为字节数组的结构编写自定义代码来解决问题,但这样做相当繁琐,我不禁觉得有一些通用的解决方案。
答案 0 :(得分: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();
}