mirror-ac/server/Helper.cs

89 lines
2.4 KiB
C#
Raw Normal View History

2023-09-10 18:30:46 +02:00
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Serilog;
using System;
2023-09-02 17:56:46 +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 server
{
2023-09-08 20:41:11 +02:00
public class Helper
{
2023-09-10 18:30:46 +02:00
unsafe public static T BytesToStructure<T>(byte[] buffer, int offset)
2023-09-08 20:41:11 +02:00
{
2023-09-10 18:30:46 +02:00
int typeSize = Marshal.SizeOf(typeof(T));
if (buffer.Length == 0)
return default(T);
2023-09-08 20:41:11 +02:00
IntPtr ptr = Marshal.AllocHGlobal(typeSize);
try
{
Marshal.Copy(buffer, offset, ptr, typeSize);
2023-09-10 18:30:46 +02:00
T result = (T)Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
return result;
2023-09-08 20:41:11 +02:00
}
2023-09-10 18:30:46 +02:00
catch(Exception ex)
2023-09-08 20:41:11 +02:00
{
2023-09-10 18:30:46 +02:00
Log.Information(ex.Message);
return default(T);
2023-09-08 20:41:11 +02:00
}
}
2023-09-09 19:26:19 +02:00
unsafe public static byte[] StructureToBytes<T>(ref T structure)
{
int typeSize = Marshal.SizeOf(typeof(T));
byte[] buffer = new byte[typeSize];
IntPtr ptr = Marshal.AllocHGlobal(typeSize);
try
{
Marshal.StructureToPtr(structure, ptr, true);
Marshal.Copy(ptr, buffer, 0, typeSize);
2023-09-10 18:30:46 +02:00
Marshal.FreeHGlobal(ptr);
2023-09-09 19:26:19 +02:00
return buffer;
}
2023-09-10 18:30:46 +02:00
catch (Exception ex)
2023-09-09 19:26:19 +02:00
{
2023-09-10 18:30:46 +02:00
Log.Information(ex.Message);
return null;
2023-09-09 19:26:19 +02:00
}
}
2023-09-08 20:41:11 +02:00
unsafe public static string FixedUnsafeBufferToSafeString(ref byte[] buffer, int bufferSize, int offset, int stringSize)
{
if (stringSize > bufferSize)
return null;
char[] stringBuffer = new char[stringSize];
for (int i = 0; i < stringSize; i++)
{
stringBuffer[i] = (char)buffer[offset + i];
}
return new string(stringBuffer);
}
2023-09-23 13:25:48 +02:00
unsafe public static void CopyMemory(ref byte[] source, ref byte[] destination, int size, int offset)
{
if (size > destination.Length)
return;
for (int i=0; i < size; i++)
{
destination[i] = source[i + offset];
}
}
2023-09-08 20:41:11 +02:00
}
2023-09-02 17:56:46 +02:00
}
#pragma warning restore CS8600
#pragma warning restore CS8603