diff --git a/bridge.go b/bridge.go index d329440..6fcd480 100644 --- a/bridge.go +++ b/bridge.go @@ -502,3 +502,17 @@ func Error(v interface{}) (errVal error, err error) { return errors.New(str), nil } + +func UintArray(v interface{}) *[]uint { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Slice { + panic("not a slice") + } + + buf := make([]uint, rv.Len(), rv.Len()) + for i := 0; i < rv.Len(); i++ { + buf[i] = uint(rv.Index(i).Uint()) + } + + return &buf +} diff --git a/examples/caller/main.go b/examples/caller/main.go index 821ad9e..6124257 100644 --- a/examples/caller/main.go +++ b/examples/caller/main.go @@ -60,15 +60,15 @@ func main() { } log.Println(bytes) - res, err = b.CallFunc("getError", nil) + res, err = b.CallFunc("bytes", []interface{}{wasm.UintArray(bytes)}) if err != nil { panic(err) } - verr, err := wasm.Error(res) + nb, err := wasm.Bytes(res) if err != nil { panic(err) } - log.Println(verr) + log.Println(nb) } diff --git a/examples/wasm/main.go b/examples/wasm/main.go index c8bc057..3060131 100644 --- a/examples/wasm/main.go +++ b/examples/wasm/main.go @@ -7,6 +7,8 @@ import ( "errors" "log" "syscall/js" + + "github.com/vedhavyas/go-wasm/go-converts" ) func addition(this js.Value, args []js.Value) interface{} { @@ -33,6 +35,12 @@ func getError(this js.Value, args []js.Value) interface{} { return err.Error() } +func receiveSendBytes(this js.Value, args []js.Value) interface{} { + b := args[0] + buf := converts.ToBytes(b) + return js.TypedArrayOf(buf) +} + func main() { ch := make(chan bool) @@ -41,6 +49,7 @@ func main() { js.Global().Set("multiplier", js.FuncOf(multiplier)) js.Global().Set("getBytes", js.FuncOf(getBytes)) js.Global().Set("getError", js.FuncOf(getError)) + js.Global().Set("bytes", js.FuncOf(receiveSendBytes)) res := js.Global().Get("addProxy").Invoke(1, 2) log.Printf("1 + 2 = %d\n", res.Int()) diff --git a/examples/wasm/main.wasm b/examples/wasm/main.wasm index c5cf12d..51d65fc 100755 Binary files a/examples/wasm/main.wasm and b/examples/wasm/main.wasm differ diff --git a/go-converts/wasm.go b/go-converts/wasm.go new file mode 100644 index 0000000..94ac596 --- /dev/null +++ b/go-converts/wasm.go @@ -0,0 +1,14 @@ +// +build js,wasm + +package converts + +import "syscall/js" + +func ToBytes(v js.Value) []byte { + buf := make([]byte, v.Length(), v.Length()) + for i := 0; i < v.Length(); i++ { + buf[i] = byte(v.Index(i).Int()) + } + + return buf +}