Created
June 21, 2023 15:18
-
-
Save ehfeng/d6000ba41d14008eab88f055782dae2c to your computer and use it in GitHub Desktop.
How pointers works with primitives vs objects in v8go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
v8 "rogchap.com/v8go" | |
) | |
func main() { | |
iso := v8.NewIsolate() | |
ctx1 := v8.NewContext(iso) | |
ctx2 := v8.NewContext(iso) | |
// primitives are copied, but the old pointers to still point to the old ones | |
v1, err := v8.NewValue(iso, int32(1)) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("ctx1 value", v1) | |
if err := ctx2.Global().Set("x", v1); err != nil { | |
panic(err) | |
} | |
v2, err := ctx2.Global().Get("x") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("ctx2 value", v2) | |
if _, err := ctx2.RunScript("x++", "main.js"); err != nil { | |
panic(err) | |
} | |
fmt.Println("post-increment ctx2 value", v2) | |
incrementedV2, err := ctx2.Global().Get("x") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("incremented ctx2 value", incrementedV2) | |
fmt.Println("ctx1 value after increment", v1) | |
// values are copied, are pointers to objects shared? | |
fmt.Printf("\n\nObject stuff\n\n") | |
objPtr, err := v8.JSONParse(ctx1, `{"a": 1}`) | |
if err != nil { | |
panic(err) | |
} | |
s, err := v8.JSONStringify(ctx1, objPtr) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("ctx1", s) | |
if err := ctx2.Global().Set("x", objPtr); err != nil { | |
panic(err) | |
} | |
if _, err := ctx2.RunScript("x.a++", "main.js"); err != nil { | |
panic(err) | |
} | |
objPtr2, err := ctx2.Global().Get("x") | |
if err != nil { | |
panic(err) | |
} | |
s2, err := v8.JSONStringify(ctx2, objPtr2) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("ctx2, should be two", s2) | |
s, err = v8.JSONStringify(ctx1, objPtr) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("ctx1", s) | |
// yes, pointers reference the same object across contexts | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment