This repository was archived by the owner on Dec 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaScriptEngine.cs
More file actions
64 lines (53 loc) · 1.38 KB
/
JavaScriptEngine.cs
File metadata and controls
64 lines (53 loc) · 1.38 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
using System.Runtime.ExceptionServices;
using static JavaScript.v8.NativeMethods;
namespace JavaScript.v8;
public unsafe sealed class JavaScriptEngine : IDisposable
{
private IntPtr _isolate;
public JavaScriptEngine()
{
_isolate = js_isolate_new();
}
public void Run(JavaScriptScopeAction action)
{
ExceptionDispatchInfo exception = null;
js_run_in_context(_isolate, (scope, global) =>
{
try
{
action(scope, global);
}
catch (Exception ex)
{
exception = ExceptionDispatchInfo.Capture(ex);
}
});
exception?.Throw();
}
public T Run<T>(JavaScriptScopeAction<T> action)
{
T result = default;
ExceptionDispatchInfo exception = null;
js_run_in_context(_isolate, (scope, global) =>
{
try
{
result = action(scope, global);
}
catch (Exception ex)
{
exception = ExceptionDispatchInfo.Capture(ex);
}
});
exception?.Throw();
return result;
}
public void Dispose()
{
GC.SuppressFinalize(this);
if (Interlocked.CompareExchange(ref _isolate, default, default) != default)
{
js_isolate_delete(_isolate);
}
}
}