KopMap/Assets/MindPowerSdk/Base/StructReader.cs
2025-04-03 02:30:16 +08:00

51 lines
1.4 KiB
C#

using System.IO;
using System.Runtime.InteropServices;
namespace MindPowerSdk
{
public static class StructReader
{
public static T ReadStruct<T>(BinaryReader reader)
{
byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
public static T ReadStructFromArray<T>(byte[] bytes)
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
public static T[] ReadStructArray<T>(BinaryReader reader, int size)
{
T[] theStructures = new T[size];
for (int i = 0; i < size; i++)
{
theStructures[i] = ReadStruct<T>(reader);
}
return theStructures;
}
public static T[] ReadStructArray<T>(BinaryReader reader, uint size)
{
T[] theStructures = new T[size];
for (uint i = 0; i < size; i++)
{
theStructures[i] = ReadStruct<T>(reader);
}
return theStructures;
}
}
}