forked from donnaskiez/ac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHelper.cs
89 lines (75 loc) · 2.43 KB
/
Helper.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Serilog;
using System;
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
{
public class Helper
{
unsafe public static T BytesToStructure<T>(byte[] buffer, int offset)
{
int typeSize = Marshal.SizeOf(typeof(T));
if (buffer.Length == 0)
return default(T);
IntPtr ptr = Marshal.AllocHGlobal(typeSize);
try
{
Marshal.Copy(buffer, offset, ptr, typeSize);
T result = (T)Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
return result;
}
catch(Exception ex)
{
Log.Information(ex.Message);
return default(T);
}
}
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);
Marshal.FreeHGlobal(ptr);
return buffer;
}
catch (Exception ex)
{
Log.Information(ex.Message);
return null;
}
}
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);
}
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];
}
}
}
}
#pragma warning restore CS8600
#pragma warning restore CS8603