如何通过一个操作将字节数组转换为联合结构
本文关键字:转换 数组 字节数 结构 字节 何通过 操作 一个 | 更新日期: 2023-09-27 18:18:22
我在c#中声明了类似c++中的联合的东西:
[StructLayout(LayoutKind.Explicit, Size = 5)]
public struct Marker
{
[FieldOffset(0)] public byte label;
[FieldOffset(1)] public int count;
[FieldOffset(1)] private byte count_0;
[FieldOffset(2)] private byte count_1;
[FieldOffset(3)] private byte count_2;
[FieldOffset(4)] private byte count_3;
}
我也有byte[] bytes
与尺寸5。我需要将数组转换为Marker对象。我可以这样做:
var marker = new Marker
{
label = bytes[0],
count = BitConverter.ToInt32(bytes, 1)
}
或:
var marker = new Marker
{
label = bytes[0],
count_0 = bytes[1],
count_1 = bytes[2],
count_2 = bytes[3],
count_3 = bytes[4]
}
那没关系,但我认为从性能角度来看,可以通过更优化的方式做到-只是点marker
到bytes
的第一个字节。我试图找到这样的东西:
BitConverter.To<Marker>(bytes);
如何将字节数组转换为联合结构的一个操作?
应该可以了
static void Main(string[] args)
{
//Creating test data
List<byte> data = new List<byte>();
data.Add(123);
data.AddRange(BitConverter.GetBytes((int)123456));
//Converting test data to Struct
Marker m = StructFromBytes<Marker>(data.ToArray());
//Check if it works
Console.WriteLine(m.label); //Prints 123
Console.WriteLine(m.count); //Prints 123456
}
private static T StructFromBytes<T>(byte[] bytes)
{
int structSize = Marshal.SizeOf(typeof(T));
byte[] structBytes = new byte[structSize];
Array.Copy(bytes, 0, structBytes, 0, structSize);
GCHandle handle = GCHandle.Alloc(structBytes, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
你可以创建一个构造函数:
[StructLayout(LayoutKind.Explicit, Size = 5)]
public struct Marker
{
[FieldOffset(0)] public byte label;
[FieldOffset(1)] public int count;
[FieldOffset(1)] private byte count_0;
[FieldOffset(2)] private byte count_1;
[FieldOffset(3)] private byte count_2;
[FieldOffset(4)] private byte count_3;
public Marker(byte[] bytes)
{
label = bytes[0];
count_0 = bytes[1];
count_1 = bytes[2];
count_2 = bytes[3];
count_3 = bytes[4];
}
}
或操作符重载:
[StructLayout(LayoutKind.Explicit, Size = 5)]
public struct Marker
{
[FieldOffset(0)] public byte label;
[FieldOffset(1)] public int count;
[FieldOffset(1)] private byte count_0;
[FieldOffset(2)] private byte count_1;
[FieldOffset(3)] private byte count_2;
[FieldOffset(4)] private byte count_3;
public static explicit operator Marker(byte[] bytes)
{
Marker result = new Marker();
result.label = bytes[0];
result.count_0 = bytes[1];
result.count_1 = bytes[2];
result.count_2 = bytes[3];
result.count_3 = bytes[4];
return result;
}
}
这两种解决方案都可以使创建结构体变成一行代码:
Marker marker = new Marker(bytes);
Marker marker = (Marker)bytes;