1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
/// <summary>
/// Kopiert Daten aus einem Byte-Array in eine entsprechende Strukture (struct). Die Struktur muss ein sequenzeilles Layout besitzen. ( [StructLayout(LayoutKind.Sequential)]
/// </summary>
/// <param name="array">Das Byte-Array das die daten enthält</param>
/// <param name="offset">Offset ab dem die Daten in die Struktur kopiert werden sollen.</param>
/// <param name="structType">System.Type der Struktur</param>
/// <returns></returns>
static object ByteArrayToStruct(byte[] array, int offset, Type structType)
{
if (structType.StructLayoutAttribute.Value != LayoutKind.Sequential)
throw new ArgumentException("structType ist keine Struktur oder nicht Sequentiell.");
int size = Marshal.SizeOf(structType);
if (array.Length < (offset + size))
throw new ArgumentException("Byte-Array hat die falsche Länge.");
byte[] tmp = new byte[size];
Array.Copy(array, offset, tmp, 0, size);
GCHandle structHandle = GCHandle.Alloc(tmp, GCHandleType.Pinned);
object structure = Marshal.PtrToStructure(structHandle.AddrOfPinnedObject(), structType);
structHandle.Free();
return structure;
}
|