forked from lazytiger/go-v8
/
v8_context.go
96 lines (78 loc) · 2.13 KB
/
v8_context.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package v8
/*
#include "v8_wrap.h"
#include <stdlib.h>
*/
import "C"
import "unsafe"
import "runtime"
//import "reflect"
// A sandboxed execution context with its own set of built-in objects
// and functions.
type Context struct {
embedable
self unsafe.Pointer
engine *Engine
}
type ContextScope struct {
context *Context
}
func (cs ContextScope) GetEngine() *Engine {
return cs.context.engine
}
func (cs ContextScope) GetPrivateData() interface{} {
return cs.context.GetPrivateData()
}
func (cs ContextScope) SetPrivateData(data interface{}) {
cs.context.SetPrivateData(data)
}
func (e *Engine) NewContext(globalTemplate *ObjectTemplate) *Context {
var globalTemplatePtr unsafe.Pointer
if globalTemplate != nil {
globalTemplatePtr = globalTemplate.self
}
self := C.V8_NewContext(e.self, globalTemplatePtr)
if self == nil {
return nil
}
result := &Context{
self: self,
engine: e,
}
runtime.SetFinalizer(result, func(c *Context) {
if traceDispose {
println("v8.Context.Dispose()", c.self)
}
C.V8_DisposeContext(c.self)
})
return result
}
//export go_context_scope_callback
func go_context_scope_callback(c unsafe.Pointer, callback unsafe.Pointer) {
(*(*func(ContextScope))(callback))(ContextScope{(*Context)(c)})
}
func (c *Context) Scope(callback func(ContextScope)) {
C.V8_Context_Scope(c.self, unsafe.Pointer(c), unsafe.Pointer(&callback))
}
//export go_try_catch_callback
func go_try_catch_callback(callback unsafe.Pointer) {
(*(*func())(callback))()
}
func (cs ContextScope) ThrowException(err string) {
cs.Eval(`throw "` + err + `"`)
//
// TODO: use Isolate::ThrowException() will make FunctionTemplate::GetFunction() returns NULL, why?
//
//errPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&err)).Data)
//C.V8_Context_ThrowException(c.self, (*C.char)(errPtr), C.int(len(err)))
}
func (cs ContextScope) TryCatch(callback func()) error {
msg := C.V8_Context_TryCatch(cs.context.self, unsafe.Pointer(&callback))
if msg == nil {
return nil
}
return (*Message)(msg)
}
func (cs ContextScope) Global() *Object {
return newValue(cs.GetEngine(), C.V8_Context_Global(cs.context.self)).ToObject()
}