Utf8Buffer.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Text;
  4. namespace Avalonia.Platform.Interop
  5. {
  6. public class Utf8Buffer : SafeHandle
  7. {
  8. private GCHandle _gchandle;
  9. private byte[] _data;
  10. public Utf8Buffer(string s) : base(IntPtr.Zero, true)
  11. {
  12. if (s == null)
  13. return;
  14. _data = Encoding.UTF8.GetBytes(s);
  15. _gchandle = GCHandle.Alloc(_data, GCHandleType.Pinned);
  16. handle = _gchandle.AddrOfPinnedObject();
  17. }
  18. public int ByteLen => _data.Length;
  19. protected override bool ReleaseHandle()
  20. {
  21. if (handle != IntPtr.Zero)
  22. {
  23. handle = IntPtr.Zero;
  24. _data = null;
  25. _gchandle.Free();
  26. }
  27. return true;
  28. }
  29. public override bool IsInvalid => handle == IntPtr.Zero;
  30. public static unsafe string StringFromPtr(IntPtr s)
  31. {
  32. var pstr = (byte*)s;
  33. if (pstr == null)
  34. return null;
  35. int len;
  36. for (len = 0; pstr[len] != 0; len++) ;
  37. var bytes = new byte[len];
  38. Marshal.Copy(s, bytes, 0, len);
  39. return Encoding.UTF8.GetString(bytes, 0, len);
  40. }
  41. }
  42. }