FixedUtf8String.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Text;
  4. namespace Veldrid.MetalBindings
  5. {
  6. internal unsafe class FixedUtf8String : IDisposable
  7. {
  8. private GCHandle _handle;
  9. private uint _numBytes;
  10. public byte* StringPtr => (byte*)_handle.AddrOfPinnedObject().ToPointer();
  11. public FixedUtf8String(string s)
  12. {
  13. if (s == null)
  14. {
  15. throw new ArgumentNullException(nameof(s));
  16. }
  17. byte[] text = Encoding.UTF8.GetBytes(s);
  18. _handle = GCHandle.Alloc(text, GCHandleType.Pinned);
  19. _numBytes = (uint)text.Length;
  20. }
  21. public void SetText(string s)
  22. {
  23. if (s == null)
  24. {
  25. throw new ArgumentNullException(nameof(s));
  26. }
  27. _handle.Free();
  28. byte[] text = Encoding.UTF8.GetBytes(s);
  29. _handle = GCHandle.Alloc(text, GCHandleType.Pinned);
  30. _numBytes = (uint)text.Length;
  31. }
  32. private string GetString()
  33. {
  34. return Encoding.UTF8.GetString(StringPtr, (int)_numBytes);
  35. }
  36. public void Dispose()
  37. {
  38. _handle.Free();
  39. }
  40. public static implicit operator byte* (FixedUtf8String utf8String) => utf8String.StringPtr;
  41. public static implicit operator IntPtr(FixedUtf8String utf8String) => new IntPtr(utf8String.StringPtr);
  42. public static implicit operator FixedUtf8String(string s) => new FixedUtf8String(s);
  43. public static implicit operator string(FixedUtf8String utf8String) => utf8String.GetString();
  44. }
  45. }