-
Notifications
You must be signed in to change notification settings - Fork 10
/
bridge.go
75 lines (58 loc) · 1.89 KB
/
bridge.go
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
package quickjs
import (
"runtime/cgo"
"unsafe"
)
/*
#include <stdint.h>
#include "bridge.h"
*/
import "C"
//export goProxy
func goProxy(ctx *C.JSContext, thisVal C.JSValueConst, argc C.int, argv *C.JSValueConst) C.JSValue {
refs := unsafe.Slice(argv, argc) // Go 1.17 and later
// get the function
fnHandler := C.int64_t(0)
C.JS_ToInt64(ctx, &fnHandler, refs[0])
fn := cgo.Handle(fnHandler).Value().(func(ctx *Context, this Value, args []Value) Value)
// get ctx
ctxHandler := C.int64_t(0)
C.JS_ToInt64(ctx, &ctxHandler, refs[1])
ctxOrigin := cgo.Handle(ctxHandler).Value().(*Context)
// refs[0] is the id, refs[1] is the ctx
args := make([]Value, len(refs)-2)
for i := 0; i < len(args); i++ {
args[i].ctx = ctxOrigin
args[i].ref = refs[2+i]
}
result := fn(ctxOrigin, Value{ctx: ctxOrigin, ref: thisVal}, args)
return result.ref
}
//export goAsyncProxy
func goAsyncProxy(ctx *C.JSContext, thisVal C.JSValueConst, argc C.int, argv *C.JSValueConst) C.JSValue {
refs := unsafe.Slice(argv, argc) // Go 1.17 and later
// get the function
fnHandler := C.int64_t(0)
C.JS_ToInt64(ctx, &fnHandler, refs[0])
asyncFn := cgo.Handle(fnHandler).Value().(func(ctx *Context, this Value, promise Value, args []Value) Value)
// get ctx
ctxHandler := C.int64_t(0)
C.JS_ToInt64(ctx, &ctxHandler, refs[1])
ctxOrigin := cgo.Handle(ctxHandler).Value().(*Context)
args := make([]Value, len(refs)-2)
for i := 0; i < len(args); i++ {
args[i].ctx = ctxOrigin
args[i].ref = refs[2+i]
}
promise := args[0]
result := asyncFn(ctxOrigin, Value{ctx: ctxOrigin, ref: thisVal}, promise, args[1:])
return result.ref
}
//export goInterruptHandler
func goInterruptHandler(rt *C.JSRuntime, handlerArgs unsafe.Pointer) C.int {
handlerArgsStruct := (*C.handlerArgs)(handlerArgs)
hFn := cgo.Handle(handlerArgsStruct.fn)
hFnValue := hFn.Value().(InterruptHandler)
// defer hFn.Delete()
return C.int(hFnValue())
}