StructConverter.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. namespace UniversalNetFrame451;
  2. public class StructConverter
  3. {
  4. public static bool TryGetBytes<T_Struct>(T_Struct structure, out byte[] bytes) where T_Struct : struct
  5. {
  6. bytes = default;
  7. int size = Marshal.SizeOf(structure);
  8. nint buffer = Marshal.AllocHGlobal(size);
  9. try
  10. {
  11. Marshal.StructureToPtr(structure, buffer, false);
  12. bytes = new byte[size];
  13. Marshal.Copy(buffer, bytes, 0, size);
  14. return true;
  15. }
  16. catch
  17. {
  18. return false;
  19. }
  20. finally
  21. {
  22. Marshal.FreeHGlobal(buffer);
  23. }
  24. }
  25. public static bool TryGetStruct<T_Struct>(byte[] bytes, out T_Struct? structData) where T_Struct : struct
  26. {
  27. nint buffer = Marshal.AllocHGlobal(bytes.Length);
  28. try
  29. {
  30. Marshal.Copy(bytes, 0, buffer, bytes.Length);
  31. structData = Marshal.PtrToStructure<T_Struct>(buffer);
  32. return true;
  33. }
  34. catch
  35. {
  36. structData = null;
  37. return false;
  38. }
  39. finally
  40. {
  41. Marshal.FreeHGlobal(buffer);
  42. }
  43. }
  44. public static T_Struct? GetStruct<T_Struct>(byte[] bytes) where T_Struct : struct
  45. {
  46. nint buffer = Marshal.AllocHGlobal(bytes.Length);
  47. try
  48. {
  49. Marshal.Copy(bytes, 0, buffer, bytes.Length);
  50. return Marshal.PtrToStructure<T_Struct>(buffer);
  51. }
  52. catch
  53. {
  54. return null;
  55. }
  56. finally
  57. {
  58. Marshal.FreeHGlobal(buffer);
  59. }
  60. }
  61. }