/
MarshalUtility.cs
73 lines (61 loc) · 1.78 KB
/
MarshalUtility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Runtime.InteropServices;
namespace OpenToolkit.Core
{
internal static class MarshalUtility
{
public static unsafe IntPtr StringToCoTaskMemUTF8(string str)
{
#if NETSTANDARD2_0
if (str == null)
{
return IntPtr.Zero;
}
var maxByteLength = System.Text.Encoding.UTF8.GetMaxByteCount(str.Length);
var ptr = (byte*)Marshal.AllocCoTaskMem(maxByteLength + 1);
int actualLen;
fixed (char* pChar = str)
{
actualLen = System.Text.Encoding.UTF8.GetBytes(pChar, str.Length, ptr, maxByteLength);
}
ptr[actualLen] = 0;
return (IntPtr)ptr;
#else
return Marshal.StringToCoTaskMemUTF8(str);
#endif
}
/// <summary>
/// Converts a null-terminated UTF-8 string to a <see cref="string" />.
/// </summary>
/// <param name="ptr">The pointer to the null-terminated UTF-8 data.</param>
/// <returns>The string.</returns>
public static unsafe string PtrToStringUTF8(byte* ptr)
{
#if NETSTANDARD2_0
if (ptr == null)
{
return null;
}
var length = FindNullTerminator(ptr);
return System.Text.Encoding.UTF8.GetString(ptr, length);
#else
return Marshal.PtrToStringUTF8((IntPtr)ptr);
#endif
}
#if NETSTANDARD2_0
private static unsafe int FindNullTerminator(byte* ptr)
{
if (ptr == null)
{
throw new ArgumentNullException(nameof(ptr));
}
var i = 0;
while (ptr[i] != 0)
{
i++;
}
return i;
}
#endif
}
}