forked from wspl/go-quickjs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
function.go
67 lines (56 loc) · 1.6 KB
/
function.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
package quickjs
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lquickjs
#include "quickjs-bridge.h"
*/
import "C"
import "unsafe"
//export GoHandler
func GoHandler(cctx *C.JSContext, cthis C.JSValueConst, cargc C.int, cargv *C.JSValueConst) C.JSValue {
ctx := ctxMap[cctx]
cargs := (*[1 << 28]C.JSValueConst)(unsafe.Pointer(cargv))[:cargc:cargc]
id := ctx.WrapValue(cargs[0]).Int()
this := ctx.WrapValue(cthis)
var args []*JSValue
for _, carg := range cargs {
args = append(args, ctx.WrapValue(carg))
}
result, err := ctx.functions[id].fn(args, this)
if err != nil {
return err.ref
}
return result.ref
}
type JSGoFunctionCallback func(args []*JSValue, this *JSValue) (*JSValue, *JSError)
type JSGoFunction struct {
ref C.JSValue
ctx *JSContext
fn JSGoFunctionCallback
}
func NewJSGoFunction(ctx *JSContext, fn JSGoFunctionCallback) *JSGoFunction {
jsf := new(JSGoFunction)
jsf.ctx = ctx
jsf.fn = fn
jsf.init()
return jsf
}
func (jsf *JSGoFunction) init() {
wrapperScript := "(invokeGoFunction, id) => function () { return invokeGoFunction.call(this, id, arguments) }"
wrapperFn, _ := jsf.ctx.Eval(wrapperScript, "")
defer wrapperFn.Free()
id := len(jsf.ctx.functions)
jsf.ctx.functions = append(jsf.ctx.functions, jsf)
idVal := jsf.ctx.NewInt32(int32(id))
wrapperArgs := []C.JSValue{
jsf.ctx.cFunction,
idVal.ref,
}
jsf.ref = C.JS_Call(jsf.ctx.ref, wrapperFn.ref, jsf.ctx.NewNull().ref, 2, &wrapperArgs[0])
}
func (jsf *JSGoFunction) Value() *JSValue {
return jsf.ctx.WrapValue(jsf.ref)
}
func (jsf *JSGoFunction) Call(args []*JSValue, this *JSValue) *JSValue {
return jsf.Value().Call(args, this)
}