Utf8Marshaler.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #region License
  2. /* Copyright 2012 James F. Bellinger <http://www.zer7.com/software/hidsharp>
  3. Permission to use, copy, modify, and/or distribute this software for any
  4. purpose with or without fee is hereby granted, provided that the above
  5. copyright notice and this permission notice appear in all copies.
  6. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  7. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  8. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  9. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  10. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  11. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  12. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  13. #endregion
  14. using System;
  15. using System.Runtime.InteropServices;
  16. using System.Text;
  17. namespace HidSharp.Platform
  18. {
  19. sealed class Utf8Marshaler : ICustomMarshaler
  20. {
  21. bool _allocated; // workaround for Mono bug 4722
  22. public void CleanUpManagedData(object obj)
  23. {
  24. }
  25. public void CleanUpNativeData(IntPtr ptr)
  26. {
  27. if (IntPtr.Zero == ptr || !_allocated) { return; }
  28. Marshal.FreeHGlobal(ptr); _allocated = false;
  29. }
  30. public int GetNativeDataSize()
  31. {
  32. return -1;
  33. }
  34. public IntPtr MarshalManagedToNative(object obj)
  35. {
  36. string str = obj as string;
  37. if (str == null) { return IntPtr.Zero; }
  38. byte[] bytes = Encoding.UTF8.GetBytes(str);
  39. IntPtr ptr = Marshal.AllocHGlobal(bytes.Length + 1);
  40. Marshal.Copy(bytes, 0, ptr, bytes.Length);
  41. Marshal.WriteByte(ptr, bytes.Length, 0);
  42. _allocated = true; return ptr;
  43. }
  44. public object MarshalNativeToManaged(IntPtr ptr)
  45. {
  46. if (ptr == IntPtr.Zero) { return null; }
  47. int length;
  48. for (length = 0; Marshal.ReadByte(ptr, length) != 0; length++) ;
  49. byte[] bytes = new byte[length];
  50. Marshal.Copy(ptr, bytes, 0, bytes.Length);
  51. string str = Encoding.UTF8.GetString(bytes);
  52. return str;
  53. }
  54. public static ICustomMarshaler GetInstance(string cookie)
  55. {
  56. return new Utf8Marshaler();
  57. }
  58. }
  59. }