|
15 | 15 | // Refer to LICENSE for more information. |
16 | 16 |
|
17 | 17 | using System; |
| 18 | +using System.Runtime.InteropServices; |
18 | 19 | using System.Text; |
19 | 20 | using SystemMarshal = System.Runtime.InteropServices.Marshal; |
20 | 21 | using SystemGCHandle = System.Runtime.InteropServices.GCHandle; |
@@ -52,31 +53,35 @@ public void Dispose() |
52 | 53 | } |
53 | 54 |
|
54 | 55 | /// <summary> |
55 | | - /// Interpret a zero terminated c string as UTF-8. |
| 56 | + /// Interpret a zero-terminated c string as UTF-8. |
56 | 57 | /// </summary> |
57 | | - public unsafe static string PtrToStringUTF8(IntPtr strPtr) |
| 58 | + public static unsafe string PtrToStringUTF8(IntPtr strPtr) |
58 | 59 | { |
59 | 60 | if (strPtr == IntPtr.Zero) |
60 | 61 | { |
61 | 62 | return null; |
62 | 63 | } |
63 | 64 |
|
64 | | - // TODO: Is there a built in / vectorized / better way to implement this? |
| 65 | +#if NET6_0_OR_GREATER |
| 66 | + var span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)strPtr); |
| 67 | + return Encoding.UTF8.GetString(span); |
| 68 | +#else |
65 | 69 | byte* pTraverse = (byte*)strPtr; |
66 | | - while (*pTraverse != 0) { pTraverse += 1; } |
| 70 | + while (*pTraverse != 0) pTraverse++; |
67 | 71 | var length = (int)(pTraverse - (byte*)strPtr); |
68 | 72 |
|
69 | | - return Encoding.UTF8.GetString((byte*)strPtr.ToPointer(), length); |
| 73 | + return Encoding.UTF8.GetString((byte*)strPtr, length); |
| 74 | +#endif |
70 | 75 | } |
71 | 76 |
|
72 | | - public unsafe static string PtrToStringUTF8(IntPtr strPtr, UIntPtr strLength) |
| 77 | + public static unsafe string PtrToStringUTF8(IntPtr strPtr, UIntPtr strLength) |
73 | 78 | { |
74 | 79 | if (strPtr == IntPtr.Zero) |
75 | 80 | { |
76 | 81 | return null; |
77 | 82 | } |
78 | 83 |
|
79 | | - return Encoding.UTF8.GetString((byte*)strPtr.ToPointer(), (int)strLength); |
| 84 | + return Encoding.UTF8.GetString((byte*)strPtr, (int)strLength); |
80 | 85 | } |
81 | 86 |
|
82 | 87 | public static T PtrToStructure<T>(IntPtr ptr) |
|
0 commit comments