fixed performance bug for function callback

This commit is contained in:
Star 2024-07-03 16:13:34 +08:00
parent 176aee6189
commit d94196060c
2 changed files with 22 additions and 3 deletions

View File

@ -20,6 +20,7 @@ type Context struct {
globals *Value globals *Value
proxy *Value proxy *Value
asyncProxy *Value asyncProxy *Value
handles map[int64]any // add by Star
} }
// Runtime returns the runtime of the context. // Runtime returns the runtime of the context.
@ -41,6 +42,14 @@ func (ctx *Context) Close() {
ctx.globals.Free() ctx.globals.Free()
} }
// add by Star
for _, hv := range ctx.handles {
if h, ok := hv.(cgo.Handle); ok {
h.Delete()
}
}
ctx.handles = nil
C.JS_FreeContext(ctx.ref) C.JS_FreeContext(ctx.ref)
} }
@ -162,8 +171,16 @@ func (ctx *Context) Function(fn func(ctx *Context, this Value, args []Value) Val
} }
} }
fnHandler := ctx.Int64(int64(cgo.NewHandle(fn))) // edit by Star
ctxHandler := ctx.Int64(int64(cgo.NewHandle(ctx))) //fnHandler := ctx.Int64(int64(cgo.NewHandle(fn)))
//ctxHandler := ctx.Int64(int64(cgo.NewHandle(ctx)))
fnH := cgo.NewHandle(fn)
ctxH := cgo.NewHandle(ctx)
ctx.handles[int64(fnH)] = fnH
ctx.handles[int64(ctxH)] = ctxH
fnHandler := ctx.Int64(int64(fnH))
ctxHandler := ctx.Int64(int64(ctxH))
args := []C.JSValue{ctx.proxy.ref, fnHandler.ref, ctxHandler.ref} args := []C.JSValue{ctx.proxy.ref, fnHandler.ref, ctxHandler.ref}
val, err := ctx.Eval(`(proxy, fnHandler, ctx) => function() { return proxy.call(this, fnHandler, ctx, ...arguments); }`) val, err := ctx.Eval(`(proxy, fnHandler, ctx) => function() { return proxy.call(this, fnHandler, ctx, ...arguments); }`)

View File

@ -177,5 +177,7 @@ func (r Runtime) NewContext() *Context {
C.JS_FreeValue(ctx_ref, init_run) C.JS_FreeValue(ctx_ref, init_run)
// C.js_std_loop(ctx_ref) // C.js_std_loop(ctx_ref)
return &Context{ref: ctx_ref, runtime: &r} // edit by Star
//return &Context{ref: ctx_ref, runtime: &r}
return &Context{ref: ctx_ref, runtime: &r, handles: map[int64]any{}}
} }