mirror-ac/service/helper.cs

42 lines
1 KiB
C#
Raw Normal View History

2023-09-10 19:32:12 +02:00
using Serilog;
using System;
2023-08-23 17:16:13 +02:00
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
#pragma warning disable CS8600
#pragma warning disable CS8603
namespace service
{
public class Helper
{
2023-09-10 19:32:12 +02:00
unsafe public static T BytesToStructure<T>(byte[] buffer, int offset)
2023-08-23 17:16:13 +02:00
{
int typeSize = Marshal.SizeOf(typeof(T));
2023-09-10 19:32:12 +02:00
if (buffer.Length == 0)
return default(T);
2023-08-23 17:16:13 +02:00
IntPtr ptr = Marshal.AllocHGlobal(typeSize);
try
{
2023-09-02 18:55:40 +02:00
Marshal.Copy(buffer, offset, ptr, typeSize);
2023-09-10 19:32:12 +02:00
T result = (T)Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
return result;
2023-08-23 17:16:13 +02:00
}
2023-09-10 19:32:12 +02:00
catch (Exception ex)
2023-08-23 17:16:13 +02:00
{
2023-09-10 19:32:12 +02:00
Log.Information(ex.Message);
return default(T);
2023-08-23 17:16:13 +02:00
}
}
}
}
#pragma warning restore CS8600
#pragma warning restore CS8603