Helper.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Uestc.Auto6.Dso.Hardware.Calibration.Data.Base
  4. {
  5. public class Helper
  6. {
  7. #region Marshal
  8. internal static byte[] StructToBytes(object structObj)
  9. {
  10. int size = Marshal.SizeOf(structObj);
  11. IntPtr buffer = Marshal.AllocHGlobal(size);
  12. try
  13. {
  14. Marshal.StructureToPtr(structObj, buffer, false);
  15. byte[] bytes = new byte[size];
  16. Marshal.Copy(buffer, bytes, 0, size);
  17. return bytes;
  18. }
  19. finally
  20. {
  21. Marshal.FreeHGlobal(buffer);
  22. }
  23. }
  24. internal static T? BytesToStruct<T>(byte[] bytes, int startIndex, Type strcutType)
  25. {
  26. int size = Marshal.SizeOf(strcutType);
  27. T? data;
  28. IntPtr buffer = Marshal.AllocHGlobal(size);
  29. try
  30. {
  31. Marshal.Copy(bytes, startIndex, buffer, size);
  32. data=(T?)Marshal.PtrToStructure(buffer, strcutType);
  33. }
  34. catch
  35. {
  36. data = (T?)Activator.CreateInstance(strcutType, new object[] { });
  37. }
  38. finally
  39. {
  40. Marshal.FreeHGlobal(buffer);
  41. }
  42. return data;
  43. }
  44. #endregion
  45. public static ICaliData? GetICaliData(CaliDataType caliDataType)
  46. {
  47. return caliDataType switch
  48. {
  49. CaliDataType.PhyChannel => ChannelParams.Default,
  50. CaliDataType.TiAdc_SyncSampleClock => TiAdc_SyncSampleClock.Default,
  51. CaliDataType.TiAdc_PhaseOffsetGain => TiAdc_PhaseOffsetGain.Default,
  52. CaliDataType.CoefficientsTable_AFC => CoefficientsTable_AFC.Default,
  53. CaliDataType.CoefficientsTable_Interpolation => CoefficientsTable_Interpolation.Default,
  54. CaliDataType.CoefficientsTable_TiAdc => CoefficientsTable_TiAdc.Default,
  55. CaliDataType.Misc =>MiscData.Default,
  56. _ => null
  57. };
  58. }
  59. public static ICoefficientsTable? GetICoefficientsTable(CaliDataType caliDataType)
  60. {
  61. return caliDataType switch
  62. {
  63. CaliDataType.CoefficientsTable_AFC => CoefficientsTable_AFC.Default,
  64. CaliDataType.CoefficientsTable_Interpolation => CoefficientsTable_Interpolation.Default,
  65. CaliDataType.CoefficientsTable_TiAdc => CoefficientsTable_TiAdc.Default,
  66. _ => null
  67. };
  68. }
  69. }
  70. }