MarshalHelper.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Urho
  4. {
  5. public static class MarshalHelper
  6. {
  7. public static unsafe float ReadSingle(this IntPtr ptr, int offset)
  8. {
  9. if (sizeof (IntPtr) == sizeof (int))
  10. {
  11. var value32 = Marshal.ReadInt32(ptr, offset);
  12. return *(float*)&value32;
  13. }
  14. var value64 = Marshal.ReadInt64(ptr, offset);
  15. return (float)*(double*) &value64;
  16. }
  17. public static float[] ToFloatsArray(this IntPtr ptr, int size)
  18. {
  19. float[] result = new float[size];
  20. Marshal.Copy(ptr, result, 0, size);
  21. return result;
  22. }
  23. public static byte[] ToBytesArray(this IntPtr ptr, int size)
  24. {
  25. byte[] result = new byte[size];
  26. Marshal.Copy(ptr, result, 0, size);
  27. return result;
  28. }
  29. public static int[] ToIntsArray(this IntPtr ptr, int size)
  30. {
  31. int[] result = new int[size];
  32. Marshal.Copy(ptr, result, 0, size);
  33. return result;
  34. }
  35. public static T[] ToStructsArray<T>(this IntPtr ptr, int size) where T : struct
  36. {
  37. T[] result = new T[size];
  38. var typeSize = Marshal.SizeOf(typeof (T));
  39. for (int i = 0; i < size; i++)
  40. {
  41. var currentPtr = Marshal.ReadIntPtr(ptr, typeSize*i);
  42. result[i] = (T)Marshal.PtrToStructure(currentPtr, typeof (T));
  43. }
  44. return result;
  45. }
  46. }
  47. }