@nativescript/windows 0.1.0-alpha.7 → 0.1.0-alpha.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build.ps1 +44 -2
- package/framework/__PROJECT_NAME__/App.xaml.cs +67 -22
- package/framework/__PROJECT_NAME__/Assets/SplashScreen.png +0 -0
- package/framework/__PROJECT_NAME__/Assets/Square150x150Logo.png +0 -0
- package/framework/__PROJECT_NAME__/Assets/Square44x44Logo.png +0 -0
- package/framework/__PROJECT_NAME__/Assets/StoreLogo.png +0 -0
- package/framework/__PROJECT_NAME__/Assets/Wide310x150Logo.png +0 -0
- package/framework/__PROJECT_NAME__/CrashDiagnostics.cs +262 -66
- package/framework/__PROJECT_NAME__/Package.appxmanifest +2 -5
- package/framework/__PROJECT_NAME__/RuntimeHost.cs +132 -22
- package/framework/__PROJECT_NAME__/__PROJECT_NAME__.csproj +49 -12
- package/framework/dotnet-bridge/BinaryProtocol.cs +145 -0
- package/framework/dotnet-bridge/Bridge.BinaryDispatch.cs +203 -0
- package/framework/dotnet-bridge/Bridge.Dispatch.cs +433 -0
- package/framework/dotnet-bridge/Bridge.JsDelegate.cs +96 -0
- package/framework/dotnet-bridge/Bridge.TaskHelper.cs +207 -0
- package/framework/dotnet-bridge/Bridge.cs +287 -286
- package/framework/dotnet-bridge/DispatchTypes.cs +304 -0
- package/framework/libs/arm64/nativescript.dll +0 -0
- package/framework/libs/devtools/arm64/nativescript.dll +0 -0
- package/framework/libs/devtools/x64/nativescript.dll +0 -0
- package/framework/libs/x64/nativescript.dll +0 -0
- package/framework/tools/dotnet-tool-arm64.exe +0 -0
- package/framework/tools/dotnet-tool-x64.exe +0 -0
- package/framework/tools/dotnet-tool.exe +0 -0
- package/package.json +19 -19
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
using System;
|
|
2
|
+
using System.Buffers;
|
|
3
|
+
using System.Collections;
|
|
4
|
+
using System.Collections.Generic;
|
|
5
|
+
using System.Linq;
|
|
6
|
+
using System.Linq.Expressions;
|
|
7
|
+
using System.Reflection;
|
|
8
|
+
using System.Runtime.InteropServices;
|
|
9
|
+
using System.Text.Json;
|
|
10
|
+
using System.Threading;
|
|
11
|
+
using System.Threading.Tasks;
|
|
12
|
+
|
|
13
|
+
namespace NativeScriptBridge;
|
|
14
|
+
|
|
15
|
+
public static partial class Bridge
|
|
16
|
+
{
|
|
17
|
+
internal static DispatchResult Dispatch(InvokeRequest req)
|
|
18
|
+
{
|
|
19
|
+
var method = req.Method ?? throw new ArgumentException("Method is required");
|
|
20
|
+
|
|
21
|
+
if (method == "__release" && req.Handle.HasValue)
|
|
22
|
+
{
|
|
23
|
+
s_handles.TryRemove(req.Handle.Value, out _);
|
|
24
|
+
return DispatchResult.Void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
object? target = null;
|
|
28
|
+
Type type;
|
|
29
|
+
|
|
30
|
+
if (req.Handle.HasValue)
|
|
31
|
+
{
|
|
32
|
+
if (!s_handles.TryGetValue(req.Handle.Value, out target))
|
|
33
|
+
throw new KeyNotFoundException($"Invalid handle {req.Handle.Value}");
|
|
34
|
+
type = target?.GetType() ?? throw new InvalidOperationException("Handle refers to null");
|
|
35
|
+
}
|
|
36
|
+
else
|
|
37
|
+
{
|
|
38
|
+
type = ResolveType(req.Assembly, req.TypeName)
|
|
39
|
+
?? throw new TypeLoadException($"Type not found: {req.TypeName} (assembly: {req.Assembly})");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (method == "__members__")
|
|
43
|
+
return BuildMembersResult(type);
|
|
44
|
+
|
|
45
|
+
if (method == "__dotnet_await__" && req.Handle.HasValue)
|
|
46
|
+
{
|
|
47
|
+
var a = req.Args ?? [];
|
|
48
|
+
if (a.Length >= 2)
|
|
49
|
+
{
|
|
50
|
+
var resolveId = (int)a[0].GetInt64();
|
|
51
|
+
var rejectId = (int)a[1].GetInt64();
|
|
52
|
+
ScheduleTaskContinuation(req.Handle.Value, resolveId, rejectId);
|
|
53
|
+
}
|
|
54
|
+
return DispatchResult.Void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (method == ".ctor")
|
|
58
|
+
{
|
|
59
|
+
var argElems = req.Args ?? [];
|
|
60
|
+
var entry = GetCachedCtor(type, argElems.Length);
|
|
61
|
+
if (entry.Ctor is null)
|
|
62
|
+
throw new MissingMethodException(
|
|
63
|
+
$"No public constructor on {type.FullName} for {argElems.Length} args");
|
|
64
|
+
// ConstructorInfo.Invoke validates args.Length == paramCount exactly — no pool.
|
|
65
|
+
return Box(entry.Ctor.Invoke(BuildArgsExact(argElems, entry.Parameters)));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
var isStatic = target is null;
|
|
69
|
+
var flags = (isStatic ? BindingFlags.Static : BindingFlags.Instance) | BindingFlags.Public;
|
|
70
|
+
|
|
71
|
+
if (method.Length > 4)
|
|
72
|
+
{
|
|
73
|
+
if (method[0] == 'g' && method[1] == 'e' && method[2] == 't' && method[3] == '_')
|
|
74
|
+
{
|
|
75
|
+
var prop = GetCachedProp(type, method, 4, flags);
|
|
76
|
+
if (prop is not null) return Box(prop.GetValue(target));
|
|
77
|
+
}
|
|
78
|
+
else if (method[0] == 's' && method[1] == 'e' && method[2] == 't' && method[3] == '_'
|
|
79
|
+
&& req.Args?.Length == 1)
|
|
80
|
+
{
|
|
81
|
+
var prop = GetCachedProp(type, method, 4, flags);
|
|
82
|
+
if (prop is not null)
|
|
83
|
+
{
|
|
84
|
+
prop.SetValue(target, Coerce(req.Args[0], prop.PropertyType));
|
|
85
|
+
return DispatchResult.Void;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
var args = req.Args ?? [];
|
|
91
|
+
var dispEntry = GetCachedMethod(type, method, args.Length, flags);
|
|
92
|
+
if (dispEntry.Invoke is null)
|
|
93
|
+
throw new MissingMethodException(
|
|
94
|
+
$"Method '{method}' ({args.Length} args) not found on {type.FullName}");
|
|
95
|
+
|
|
96
|
+
var builtArgs = BuildArgs(args, dispEntry.Parameters);
|
|
97
|
+
try { return Box(AwaitIfTask(dispEntry.Invoke(target, builtArgs))); }
|
|
98
|
+
finally { if (builtArgs.Length > 0) ReturnArgs(builtArgs); }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private static DispatchEntry GetCachedMethod(Type type, string name, int argCount, BindingFlags flags)
|
|
102
|
+
=> s_methodCache.GetOrAdd(
|
|
103
|
+
new MethodKey(type, name, argCount, flags),
|
|
104
|
+
static k => BuildDispatchEntry(k.Type, k.Name, k.ArgCount, k.Flags));
|
|
105
|
+
|
|
106
|
+
private static DispatchEntry BuildDispatchEntry(Type type, string name, int argCount, BindingFlags flags)
|
|
107
|
+
{
|
|
108
|
+
var mi = FindMethodCore(type, name, argCount, flags);
|
|
109
|
+
if (mi is null) return DispatchEntry.Empty;
|
|
110
|
+
|
|
111
|
+
var parameters = mi.GetParameters();
|
|
112
|
+
|
|
113
|
+
try
|
|
114
|
+
{
|
|
115
|
+
var targetParam = Expression.Parameter(typeof(object), "t");
|
|
116
|
+
var argsParam = Expression.Parameter(typeof(object?[]), "a");
|
|
117
|
+
|
|
118
|
+
var typedArgs = parameters.Select((p, i) =>
|
|
119
|
+
(Expression)Expression.Convert(
|
|
120
|
+
Expression.ArrayIndex(argsParam, Expression.Constant(i)),
|
|
121
|
+
p.ParameterType)).ToArray();
|
|
122
|
+
|
|
123
|
+
Expression body = mi.IsStatic
|
|
124
|
+
? Expression.Call(mi, typedArgs)
|
|
125
|
+
: Expression.Call(Expression.Convert(targetParam, type), mi, typedArgs);
|
|
126
|
+
|
|
127
|
+
if (body.Type == typeof(void))
|
|
128
|
+
body = Expression.Block(typeof(object), body, Expression.Constant(null, typeof(object)));
|
|
129
|
+
else if (body.Type != typeof(object))
|
|
130
|
+
body = Expression.Convert(body, typeof(object));
|
|
131
|
+
|
|
132
|
+
var fn = Expression.Lambda<Func<object?, object?[], object?>>(
|
|
133
|
+
body, targetParam, argsParam).Compile();
|
|
134
|
+
|
|
135
|
+
return new DispatchEntry(fn, parameters);
|
|
136
|
+
}
|
|
137
|
+
catch
|
|
138
|
+
{
|
|
139
|
+
// mi.Invoke validates args.Length == paramCount; slice the rented buffer if needed.
|
|
140
|
+
int pc = parameters.Length;
|
|
141
|
+
return new DispatchEntry(
|
|
142
|
+
(t, a) => mi.Invoke(t, a.Length == pc ? a : a[..pc]),
|
|
143
|
+
parameters);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private static CtorEntry GetCachedCtor(Type type, int argCount)
|
|
148
|
+
=> s_ctorCache.GetOrAdd(new CtorKey(type, argCount), static k =>
|
|
149
|
+
{
|
|
150
|
+
var ctors = k.Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
|
|
151
|
+
var ctor = Array.Find(ctors, c => c.GetParameters().Length == k.ArgCount)
|
|
152
|
+
?? ctors.FirstOrDefault();
|
|
153
|
+
return new CtorEntry(ctor, ctor?.GetParameters() ?? []);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
private static PropertyInfo? GetCachedProp(Type type, string method, int prefixLen, BindingFlags flags)
|
|
157
|
+
=> s_propCache.GetOrAdd(
|
|
158
|
+
new PropKey(type, method[prefixLen..], flags),
|
|
159
|
+
static k => k.Type.GetProperty(k.Name, k.Flags));
|
|
160
|
+
|
|
161
|
+
// Pooled: rented array passed to the compiled delegate (which accesses by index,
|
|
162
|
+
// not by Length). Caller must return via ReturnArgs immediately after invoke.
|
|
163
|
+
private static object?[] BuildArgs(JsonElement[] elements, ParameterInfo[] parameters)
|
|
164
|
+
{
|
|
165
|
+
if (parameters.Length == 0) return [];
|
|
166
|
+
var args = ArrayPool<object?>.Shared.Rent(parameters.Length);
|
|
167
|
+
for (int i = 0; i < parameters.Length && i < elements.Length; i++)
|
|
168
|
+
args[i] = Coerce(elements[i], parameters[i].ParameterType);
|
|
169
|
+
return args;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Exact: required by ConstructorInfo.Invoke / MethodInfo.Invoke which validate
|
|
173
|
+
// args.Length == paramCount and would throw on an oversized rented buffer.
|
|
174
|
+
private static object?[] BuildArgsExact(JsonElement[] elements, ParameterInfo[] parameters)
|
|
175
|
+
{
|
|
176
|
+
if (parameters.Length == 0) return [];
|
|
177
|
+
var args = new object?[parameters.Length];
|
|
178
|
+
for (int i = 0; i < parameters.Length && i < elements.Length; i++)
|
|
179
|
+
args[i] = Coerce(elements[i], parameters[i].ParameterType);
|
|
180
|
+
return args;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private static void ReturnArgs(object?[] args) =>
|
|
184
|
+
ArrayPool<object?>.Shared.Return(args, clearArray: true);
|
|
185
|
+
|
|
186
|
+
private static object? Coerce(JsonElement el, Type targetType)
|
|
187
|
+
{
|
|
188
|
+
if (el.ValueKind == JsonValueKind.Null) return null;
|
|
189
|
+
if (el.ValueKind == JsonValueKind.Object && el.TryGetProperty("__handle", out var h))
|
|
190
|
+
{
|
|
191
|
+
s_handles.TryGetValue(h.GetInt32(), out var obj);
|
|
192
|
+
return obj;
|
|
193
|
+
}
|
|
194
|
+
return el.Deserialize(targetType, s_coerceOpts);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private static object? AwaitIfTask(object? value)
|
|
198
|
+
{
|
|
199
|
+
if (value is null) return null;
|
|
200
|
+
|
|
201
|
+
if (value is Task task)
|
|
202
|
+
{
|
|
203
|
+
task.GetAwaiter().GetResult();
|
|
204
|
+
return TaskResultCache.GetResult(task);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (value is ValueTask vt)
|
|
208
|
+
{
|
|
209
|
+
vt.AsTask().GetAwaiter().GetResult();
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
var type = value.GetType();
|
|
214
|
+
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ValueTask<>))
|
|
215
|
+
{
|
|
216
|
+
var innerTask = ValueTaskAsTaskCache.AsTask(type, value);
|
|
217
|
+
innerTask.GetAwaiter().GetResult();
|
|
218
|
+
if (innerTask.IsFaulted) throw innerTask.Exception!.InnerException ?? innerTask.Exception;
|
|
219
|
+
return TaskResultCache.GetResult(innerTask);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return value;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private static DispatchResult Box(object? value)
|
|
226
|
+
{
|
|
227
|
+
if (value is null) return DispatchResult.Void;
|
|
228
|
+
var t = value.GetType();
|
|
229
|
+
|
|
230
|
+
if (t.IsPrimitive || t == typeof(string) || t == typeof(decimal)
|
|
231
|
+
|| t == typeof(DateTime) || t == typeof(DateTimeOffset)
|
|
232
|
+
|| t == typeof(TimeSpan) || t == typeof(Guid))
|
|
233
|
+
return DispatchResult.Primitive(value, t);
|
|
234
|
+
|
|
235
|
+
if (t.IsEnum)
|
|
236
|
+
{
|
|
237
|
+
var ut = Enum.GetUnderlyingType(t);
|
|
238
|
+
return DispatchResult.Primitive(Convert.ChangeType(value, ut), ut);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (t.IsArray || (t != typeof(string) && value is IEnumerable))
|
|
242
|
+
{
|
|
243
|
+
try { return DispatchResult.Collection((IEnumerable)value); }
|
|
244
|
+
catch { }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
var id = Interlocked.Increment(ref s_nextHandle);
|
|
248
|
+
s_handles[id] = value;
|
|
249
|
+
var typeName = t.FullName ?? t.Name;
|
|
250
|
+
return IsAwaitable(value, t)
|
|
251
|
+
? DispatchResult.TaskHandle(id, typeName)
|
|
252
|
+
: DispatchResult.Handle(id, typeName);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private static bool IsAwaitable(object value, Type t)
|
|
256
|
+
{
|
|
257
|
+
if (value is Task || value is ValueTask) return true;
|
|
258
|
+
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ValueTask<>)) return true;
|
|
259
|
+
if ((t.FullName ?? "").StartsWith("Windows.Foundation.IAsync", StringComparison.Ordinal)) return true;
|
|
260
|
+
foreach (var iface in t.GetInterfaces())
|
|
261
|
+
if ((iface.FullName ?? "").StartsWith("Windows.Foundation.IAsync", StringComparison.Ordinal)) return true;
|
|
262
|
+
return t.GetMethod("GetAwaiter",
|
|
263
|
+
BindingFlags.Public | BindingFlags.Instance,
|
|
264
|
+
null, Type.EmptyTypes, null) is not null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
internal static DispatchResult BuildMembersResult(Type t)
|
|
268
|
+
{
|
|
269
|
+
const BindingFlags inst = BindingFlags.Public | BindingFlags.Instance;
|
|
270
|
+
const BindingFlags stat = BindingFlags.Public | BindingFlags.Static;
|
|
271
|
+
|
|
272
|
+
var instProps = t.GetProperties(inst);
|
|
273
|
+
var statProps = t.GetProperties(stat);
|
|
274
|
+
|
|
275
|
+
return DispatchResult.Members(
|
|
276
|
+
methods: t.GetMethods(inst).Where(m => !m.IsSpecialName).Select(m => m.Name).Distinct().ToArray(),
|
|
277
|
+
props: instProps.Where(p => p.GetGetMethod() != null).Select(p => p.Name).Distinct().ToArray(),
|
|
278
|
+
staticMethods: t.GetMethods(stat).Where(m => !m.IsSpecialName).Select(m => m.Name).Distinct().ToArray(),
|
|
279
|
+
staticProps: statProps.Where(p => p.GetGetMethod() != null).Select(p => p.Name).Distinct().ToArray(),
|
|
280
|
+
readonlyProps: instProps.Where(p => p.GetGetMethod() != null && p.GetSetMethod() == null).Select(p => p.Name).Distinct().ToArray(),
|
|
281
|
+
readonlyStaticProps: statProps.Where(p => p.GetGetMethod() != null && p.GetSetMethod() == null).Select(p => p.Name).Distinct().ToArray(),
|
|
282
|
+
writeonlyProps: instProps.Where(p => p.GetGetMethod() == null && p.GetSetMethod() != null).Select(p => p.Name).Distinct().ToArray(),
|
|
283
|
+
writeonlyStaticProps: statProps.Where(p => p.GetGetMethod() == null && p.GetSetMethod() != null).Select(p => p.Name).Distinct().ToArray()
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
internal static Type? ResolveType(string? assemblyName, string? typeName)
|
|
288
|
+
{
|
|
289
|
+
if (string.IsNullOrEmpty(typeName)) return null;
|
|
290
|
+
var key = string.IsNullOrEmpty(assemblyName) ? typeName : $"{assemblyName}|{typeName}";
|
|
291
|
+
return s_typeCache.GetOrAdd(key, _ => ResolveTypeCore(assemblyName, typeName));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private static Type? ResolveTypeCore(string? assemblyName, string? typeName)
|
|
295
|
+
{
|
|
296
|
+
if (string.IsNullOrEmpty(typeName)) return null;
|
|
297
|
+
|
|
298
|
+
// Fast/normal lookup first (assembly-qualified or plain type name).
|
|
299
|
+
var fqn = string.IsNullOrEmpty(assemblyName) ? typeName! : $"{typeName}, {assemblyName}";
|
|
300
|
+
var t = Type.GetType(fqn);
|
|
301
|
+
if (t is not null) return t;
|
|
302
|
+
|
|
303
|
+
t = Type.GetType(typeName);
|
|
304
|
+
if (t is not null) return t;
|
|
305
|
+
|
|
306
|
+
// Last segment (type name without namespace) used for loose matching below.
|
|
307
|
+
var lastDot = typeName.LastIndexOf('.');
|
|
308
|
+
var shortName = lastDot >= 0 ? typeName[(lastDot + 1)..] : typeName;
|
|
309
|
+
|
|
310
|
+
// Search loaded assemblies quickly; prefer asm.GetType which is inexpensive.
|
|
311
|
+
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
|
|
312
|
+
{
|
|
313
|
+
try
|
|
314
|
+
{
|
|
315
|
+
t = asm.GetType(typeName);
|
|
316
|
+
if (t is not null) return t;
|
|
317
|
+
|
|
318
|
+
// Fall back to scanning exported types only when necessary. Some
|
|
319
|
+
// assemblies throw on GetTypes() (ReflectionTypeLoadException) so
|
|
320
|
+
// we catch and continue.
|
|
321
|
+
foreach (var ty in asm.GetTypes())
|
|
322
|
+
{
|
|
323
|
+
if (string.Equals(ty.FullName, typeName, StringComparison.Ordinal))
|
|
324
|
+
return ty;
|
|
325
|
+
// Short-name match only when input has no namespace prefix (e.g. "Stopwatch").
|
|
326
|
+
// Guarding on lastDot < 0 prevents matching unrelated types in other namespaces
|
|
327
|
+
// (e.g. "NativeScript.Widgets.FlexboxLayout" must not match a different
|
|
328
|
+
// FlexboxLayout that happens to live in another namespace).
|
|
329
|
+
if (lastDot < 0 && string.Equals(ty.Name, shortName, StringComparison.Ordinal))
|
|
330
|
+
return ty;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
catch (ReflectionTypeLoadException) { }
|
|
334
|
+
catch { }
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// If an assembly name was provided try loading it explicitly and repeat
|
|
338
|
+
// the above search inside that assembly only (less work than scanning all).
|
|
339
|
+
if (!string.IsNullOrEmpty(assemblyName))
|
|
340
|
+
{
|
|
341
|
+
try
|
|
342
|
+
{
|
|
343
|
+
var asm = Assembly.Load(assemblyName);
|
|
344
|
+
if (asm is not null)
|
|
345
|
+
{
|
|
346
|
+
t = asm.GetType(typeName!);
|
|
347
|
+
if (t is not null) return t;
|
|
348
|
+
try
|
|
349
|
+
{
|
|
350
|
+
foreach (var ty in asm.GetTypes())
|
|
351
|
+
{
|
|
352
|
+
if (string.Equals(ty.FullName, typeName, StringComparison.Ordinal))
|
|
353
|
+
return ty;
|
|
354
|
+
if (lastDot < 0 && string.Equals(ty.Name, shortName, StringComparison.Ordinal))
|
|
355
|
+
return ty;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
catch (ReflectionTypeLoadException) { }
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
catch { }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private static MethodInfo? FindMethodCore(Type type, string name, int argCount, BindingFlags flags)
|
|
368
|
+
{
|
|
369
|
+
var match = Array.Find(type.GetMethods(flags),
|
|
370
|
+
m => m.Name == name && !m.IsGenericMethod && m.GetParameters().Length == argCount);
|
|
371
|
+
return match ?? type.GetMethod(name, flags);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
internal static Exception Unwrap(Exception ex) =>
|
|
375
|
+
ex is TargetInvocationException { InnerException: { } inner } ? Unwrap(inner) : ex;
|
|
376
|
+
|
|
377
|
+
// Used by benchmarks to give a fair end-to-end comparison of protocols.
|
|
378
|
+
|
|
379
|
+
internal static byte[] PipelineJson(ReadOnlySpan<byte> jsonRequest)
|
|
380
|
+
{
|
|
381
|
+
var req = JsonSerializer.Deserialize(jsonRequest, BridgeJsonContext.Default.InvokeRequest)!;
|
|
382
|
+
var result = Dispatch(req);
|
|
383
|
+
var buf = new ArrayBufferWriter<byte>(128);
|
|
384
|
+
using var w = new Utf8JsonWriter(buf);
|
|
385
|
+
w.WriteStartObject();
|
|
386
|
+
w.WritePropertyName("result"u8);
|
|
387
|
+
result.WriteTo(w, s_coerceOpts);
|
|
388
|
+
w.WriteEndObject();
|
|
389
|
+
w.Flush();
|
|
390
|
+
return buf.WrittenSpan.ToArray();
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
internal static byte[] PipelineBinary(ReadOnlySpan<byte> binRequest)
|
|
394
|
+
{
|
|
395
|
+
var r = new BinReader(binRequest);
|
|
396
|
+
var result = DispatchBin(ref r);
|
|
397
|
+
var buf = new ArrayBufferWriter<byte>(128);
|
|
398
|
+
result.WriteAsBin(buf);
|
|
399
|
+
return buf.WrittenSpan.ToArray();
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private static unsafe void WriteResult(DispatchResult res, byte** outPtr, int* outLen)
|
|
403
|
+
{
|
|
404
|
+
var buf = new ArrayBufferWriter<byte>(256);
|
|
405
|
+
using var w = new Utf8JsonWriter(buf);
|
|
406
|
+
w.WriteStartObject();
|
|
407
|
+
w.WritePropertyName("result"u8);
|
|
408
|
+
res.WriteTo(w, s_coerceOpts);
|
|
409
|
+
w.WriteEndObject();
|
|
410
|
+
w.Flush();
|
|
411
|
+
WriteUnmanaged(buf.WrittenSpan, outPtr, outLen);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private static unsafe void WriteError(string msg, byte** outPtr, int* outLen)
|
|
415
|
+
{
|
|
416
|
+
var buf = new ArrayBufferWriter<byte>(128);
|
|
417
|
+
using var w = new Utf8JsonWriter(buf);
|
|
418
|
+
w.WriteStartObject();
|
|
419
|
+
w.WriteString("error"u8, msg);
|
|
420
|
+
w.WriteEndObject();
|
|
421
|
+
w.Flush();
|
|
422
|
+
WriteUnmanaged(buf.WrittenSpan, outPtr, outLen);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
internal static unsafe void WriteUnmanaged(ReadOnlySpan<byte> bytes, byte** outPtr, int* outLen)
|
|
426
|
+
{
|
|
427
|
+
var p = (byte*)Marshal.AllocHGlobal(bytes.Length + 1);
|
|
428
|
+
bytes.CopyTo(new Span<byte>(p, bytes.Length));
|
|
429
|
+
p[bytes.Length] = 0;
|
|
430
|
+
*outPtr = p;
|
|
431
|
+
*outLen = bytes.Length;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
using System;
|
|
2
|
+
using System.Buffers;
|
|
3
|
+
using System.Linq;
|
|
4
|
+
using System.Linq.Expressions;
|
|
5
|
+
using System.Reflection;
|
|
6
|
+
using System.Runtime.InteropServices;
|
|
7
|
+
using System.Threading;
|
|
8
|
+
|
|
9
|
+
namespace NativeScriptBridge;
|
|
10
|
+
|
|
11
|
+
public static partial class Bridge
|
|
12
|
+
{
|
|
13
|
+
// opcode 0x09: given a delegate type name (or "" for System.Action) and a
|
|
14
|
+
// JS callback id, compile a .NET delegate that serialises its parameters as
|
|
15
|
+
// binary and calls back into V8 via the s_jsInvoker function pointer.
|
|
16
|
+
|
|
17
|
+
private static DispatchResult CreateJsDelegate(string typeName, int callbackId)
|
|
18
|
+
{
|
|
19
|
+
var delegateType = string.IsNullOrEmpty(typeName)
|
|
20
|
+
? typeof(Action)
|
|
21
|
+
: ResolveType(null, typeName)
|
|
22
|
+
?? throw new TypeLoadException($"Delegate type not found: {typeName}");
|
|
23
|
+
|
|
24
|
+
var invokeMethod = delegateType.GetMethod("Invoke")
|
|
25
|
+
?? throw new MissingMethodException($"No Invoke method on {delegateType}");
|
|
26
|
+
|
|
27
|
+
var parameters = invokeMethod.GetParameters();
|
|
28
|
+
var returnType = invokeMethod.ReturnType;
|
|
29
|
+
|
|
30
|
+
var paramExprs = parameters
|
|
31
|
+
.Select((p, i) => Expression.Parameter(p.ParameterType, p.Name ?? $"p{i}"))
|
|
32
|
+
.ToArray();
|
|
33
|
+
|
|
34
|
+
// object?[] args = new object?[] { (object?)p0, (object?)p1, … }
|
|
35
|
+
var objArgs = paramExprs.Select(p => (Expression)Expression.Convert(p, typeof(object)));
|
|
36
|
+
var argsArray = Expression.NewArrayInit(typeof(object), objArgs);
|
|
37
|
+
|
|
38
|
+
var callMethod = typeof(Bridge).GetMethod(
|
|
39
|
+
nameof(CallJsCallback),
|
|
40
|
+
BindingFlags.Static | BindingFlags.NonPublic)!;
|
|
41
|
+
|
|
42
|
+
var callExpr = Expression.Call(callMethod, Expression.Constant(callbackId), argsArray);
|
|
43
|
+
|
|
44
|
+
Expression body = returnType == typeof(void)
|
|
45
|
+
? callExpr
|
|
46
|
+
: (Expression)Expression.Block(returnType, callExpr, Expression.Default(returnType));
|
|
47
|
+
|
|
48
|
+
var del = Expression.Lambda(delegateType, body, paramExprs).Compile();
|
|
49
|
+
return Box(del);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
internal static unsafe void CallJsCallback(int id, object?[] args)
|
|
53
|
+
{
|
|
54
|
+
if (s_jsInvoker == null) return;
|
|
55
|
+
|
|
56
|
+
var buf = new ArrayBufferWriter<byte>(64);
|
|
57
|
+
var w = new BinWriter(buf);
|
|
58
|
+
w.WriteByte((byte)Math.Min(args.Length, 255));
|
|
59
|
+
foreach (var arg in args)
|
|
60
|
+
WriteCallbackArg(ref w, arg);
|
|
61
|
+
|
|
62
|
+
var bytes = buf.WrittenSpan;
|
|
63
|
+
byte* respPtr = null;
|
|
64
|
+
int respLen = 0;
|
|
65
|
+
fixed (byte* p = bytes)
|
|
66
|
+
s_jsInvoker(id, p, bytes.Length, &respPtr, &respLen);
|
|
67
|
+
|
|
68
|
+
// Response is only set for non-void delegates; free it when present.
|
|
69
|
+
if (respPtr != null && respLen > 0)
|
|
70
|
+
Marshal.FreeHGlobal((IntPtr)respPtr);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Serialises a single delegate argument in response-binary tag format so
|
|
74
|
+
// the Rust side can reuse its existing bin_read_value parser.
|
|
75
|
+
private static void WriteCallbackArg(ref BinWriter w, object? arg)
|
|
76
|
+
{
|
|
77
|
+
if (arg is null) { w.WriteByte(0x00); return; }
|
|
78
|
+
if (arg is bool b) { w.WriteByte(b ? (byte)0x02 : (byte)0x01); return; }
|
|
79
|
+
if (arg is int i) { w.WriteByte(0x03); w.WriteI32(i); return; }
|
|
80
|
+
if (arg is uint u) { w.WriteByte(0x03); w.WriteI32((int)u); return; }
|
|
81
|
+
if (arg is long l) { w.WriteByte(0x04); w.WriteF64((double)l); return; }
|
|
82
|
+
if (arg is float f) { w.WriteByte(0x04); w.WriteF64((double)f); return; }
|
|
83
|
+
if (arg is double d){ w.WriteByte(0x04); w.WriteF64(d); return; }
|
|
84
|
+
if (arg is string s){ w.WriteByte(0x05); w.WriteString32(s); return; }
|
|
85
|
+
|
|
86
|
+
// Object: box in the handle map and send as a handle reference.
|
|
87
|
+
// The JS side receives {__handle, __type} which can be turned into a
|
|
88
|
+
// proxy via NSWinRT.dotnet.fromHandle(...).
|
|
89
|
+
var handleId = Interlocked.Increment(ref s_nextHandle);
|
|
90
|
+
s_handles[handleId] = arg;
|
|
91
|
+
var typeName = arg.GetType().FullName ?? arg.GetType().Name;
|
|
92
|
+
w.WriteByte(0x06);
|
|
93
|
+
w.WriteI32(handleId);
|
|
94
|
+
w.WriteString16(typeName); // u16 length prefix (matches bin_read_value tag 0x06)
|
|
95
|
+
}
|
|
96
|
+
}
|