-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathStructExtensions.cs
58 lines (51 loc) · 1.71 KB
/
StructExtensions.cs
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
namespace RaceElement.Controls.Telemetry.SharedMemory;
/// <summary>
/// From ACManager.Tools https://github.com/gro-ove/actools/blob/master/AcManager.Tools/SharedMemory/StructExtension.cs
/// </summary>
public static class StructExtension
{
public static T ToStruct<T>(this MemoryMappedFile file, byte[] buffer)
{
using (var stream = file.CreateViewStream())
{
stream.ReadExactly(buffer);
var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
var data = Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
handle.Free();
return data;
}
}
public static T ToStruct<T>(this TimestampedBytes timestampedBytes)
{
var handle = GCHandle.Alloc(timestampedBytes.RawData, GCHandleType.Pinned);
var data = Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
handle.Free();
return data;
}
public static TimestampedBytes ToTimestampedBytes<T>(this T s, byte[] buffer) where T : struct
{
var ptr = Marshal.AllocHGlobal(buffer.Length);
Marshal.StructureToPtr(s, ptr, false);
Marshal.Copy(ptr, buffer, 0, buffer.Length);
Marshal.FreeHGlobal(ptr);
return new TimestampedBytes(buffer, DateTime.Now);
}
}
public sealed class TimestampedBytes
{
public byte[] RawData;
public DateTime IncomingDate;
public TimestampedBytes(byte[] rawData)
{
RawData = rawData;
IncomingDate = DateTime.Now;
}
public TimestampedBytes(byte[] rawData, DateTime incomingDate)
{
RawData = rawData;
IncomingDate = incomingDate;
}
}