forked from pythonnet/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodingGetStringPolyfill.cs
More file actions
53 lines (46 loc) · 2.04 KB
/
EncodingGetStringPolyfill.cs
File metadata and controls
53 lines (46 loc) · 2.04 KB
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
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace Python.Runtime
{
#if !NETSTANDARD
/// <summary>
/// This polyfill is thread unsafe.
/// </summary>
[CLSCompliant(false)]
public static class EncodingGetStringPolyfill
{
private static readonly MethodInfo PlatformGetStringMethodInfo =
typeof(Encoding).GetMethod(
"GetString",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
new[]
{
typeof(byte*), typeof(int)
}, null);
private static readonly byte[] StdDecodeBuffer = PlatformGetStringMethodInfo == null ? new byte[1024 * 1024] : null;
private static Dictionary<Encoding, EncodingGetStringUnsafeDelegate> PlatformGetStringMethodsDelegatesCache = new Dictionary<Encoding, EncodingGetStringUnsafeDelegate>();
private unsafe delegate string EncodingGetStringUnsafeDelegate(byte* pstr, int size);
public unsafe static string GetString(this Encoding encoding, byte* pstr, int size)
{
if (PlatformGetStringMethodInfo != null)
{
EncodingGetStringUnsafeDelegate getStringDelegate;
if (!PlatformGetStringMethodsDelegatesCache.TryGetValue(encoding, out getStringDelegate))
{
getStringDelegate =
(EncodingGetStringUnsafeDelegate)Delegate.CreateDelegate(
typeof(EncodingGetStringUnsafeDelegate), encoding, PlatformGetStringMethodInfo);
PlatformGetStringMethodsDelegatesCache.Add(encoding, getStringDelegate);
}
return getStringDelegate(pstr, size);
}
byte[] buffer = size <= StdDecodeBuffer.Length ? StdDecodeBuffer : new byte[size];
Marshal.Copy((IntPtr)pstr, buffer, 0, size);
return encoding.GetString(buffer, 0, size);
}
}
#endif
}