OfflineRecognizerResult.cs
2.6 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/// Copyright (c) 2024.5 by 东风破
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace SherpaOnnx
{
public class OfflineRecognizerResult
{
public OfflineRecognizerResult(IntPtr handle)
{
Impl impl = (Impl)Marshal.PtrToStructure(handle, typeof(Impl));
// PtrToStringUTF8() requires .net standard 2.1
// _text = Marshal.PtrToStringUTF8(impl.Text);
int length = 0;
unsafe
{
byte* buffer = (byte*)impl.Text;
while (*buffer != 0)
{
++buffer;
length += 1;
}
}
byte[] stringBuffer = new byte[length];
Marshal.Copy(impl.Text, stringBuffer, 0, length);
_text = Encoding.UTF8.GetString(stringBuffer);
_tokens = new String[impl.Count];
unsafe
{
byte* buf = (byte*)impl.Tokens;
for (int i = 0; i < impl.Count; i++)
{
length = 0;
byte* start = buf;
while (*buf != 0)
{
++buf;
length += 1;
}
++buf;
stringBuffer = new byte[length];
fixed (byte* pTarget = stringBuffer)
{
for (int k = 0; k < length; k++)
{
pTarget[k] = start[k];
}
}
_tokens[i] = Encoding.UTF8.GetString(stringBuffer);
}
}
unsafe
{
if (impl.Timestamps != IntPtr.Zero)
{
float *t = (float*)impl.Timestamps;
_timestamps = new float[impl.Count];
fixed (float* f = _timestamps)
{
for (int k = 0; k < impl.Count; k++)
{
f[k] = t[k];
}
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
struct Impl
{
public IntPtr Text;
public IntPtr Timestamps;
public int Count;
public IntPtr Tokens;
}
private String _text;
public String Text => _text;
private String[] _tokens;
public String[] Tokens => _tokens;
private float[] _timestamps;
public float[] Timestamps => _timestamps;
}
}