go-wasm/examples/function-caller/main.go

75 lines
1.2 KiB
Go
Raw Normal View History

2019-08-06 16:03:11 +03:00
package main
import (
2019-08-22 05:24:07 +03:00
"context"
2019-08-06 16:03:11 +03:00
"log"
2019-08-21 00:41:49 +03:00
"github.com/vedhavyas/go-wasm"
2019-08-06 16:03:11 +03:00
)
2019-08-22 05:24:07 +03:00
func addProxy(b *wasm.Bridge) wasm.Func {
2019-08-20 22:20:20 +03:00
return func(args []interface{}) (i interface{}, e error) {
2019-08-20 23:47:40 +03:00
log.Println("In Go", args)
2019-08-20 22:20:20 +03:00
return b.CallFunc("addition", args)
}
}
2019-08-22 05:24:07 +03:00
func multiply(b *wasm.Bridge, a int) (int, error) {
m, err := b.CallFunc("multiplier", nil)
if err != nil {
return 0, err
}
return a * int(m.(float64)), nil
}
2019-08-06 16:03:11 +03:00
func main() {
2019-09-24 00:37:59 +03:00
b, err := wasm.BridgeFromFile("test", "./examples/function-wasm/main.wasm", nil)
2019-08-06 16:03:11 +03:00
if err != nil {
2019-08-22 05:24:07 +03:00
panic(err)
2019-08-06 16:03:11 +03:00
}
2019-08-22 05:24:07 +03:00
err = b.SetFunc("addProxy", addProxy(b))
2019-08-20 22:20:20 +03:00
if err != nil {
panic(err)
}
2019-08-22 05:24:07 +03:00
init := make(chan error)
ctx, cancF := context.WithCancel(context.Background())
defer cancF()
go b.Run(ctx, init)
2019-08-20 04:35:19 +03:00
err = <-init
if err != nil {
panic(err)
}
2019-08-22 05:24:07 +03:00
mul, err := multiply(b, 10)
if err != nil {
panic(err)
}
log.Printf("Multiplier: %v\n", mul)
2019-08-22 20:05:05 +03:00
res, err := b.CallFunc("getBytes", nil)
if err != nil {
panic(err)
}
bytes, err := wasm.Bytes(res)
if err != nil {
panic(err)
}
2019-08-22 20:12:14 +03:00
log.Println(bytes)
2019-08-22 20:05:05 +03:00
2019-08-23 20:19:32 +03:00
res, err = b.CallFunc("bytes", []interface{}{wasm.UintArray(bytes)})
2019-08-22 20:05:05 +03:00
if err != nil {
panic(err)
}
2019-08-23 20:19:32 +03:00
nb, err := wasm.Bytes(res)
2019-08-22 20:05:05 +03:00
if err != nil {
panic(err)
}
2019-08-23 20:19:32 +03:00
log.Println(nb)
2019-08-06 16:03:11 +03:00
}