package main
func main() {
}
// 這里指定導(dǎo)出函數(shù)名 后面需要用到
//go:export fib
func Fib(n int) int {
if n == 0 || n == 1{
return 1
}
var arr = make([]int, n + 1)
arr[0], arr[1] = 1, 1
for i := 2;i<=n;i++{
arr[i] = arr[i - 1] + arr[i - 2]
}
return arr[n]
}
編譯wasmer-go/wasmer能用的需要使用到tinygo,
安裝tinygo
命令行執(zhí)行編譯
tinygo build -o ./module.wasm -target wasi .
module.wasm為導(dǎo)出的文件名
go 調(diào)用wasm
package main
import (
"fmt"
wasmer "github.com/wasmerio/wasmer-go/wasmer"
"io/ioutil"
"time"
)
func main() {
wasmBytes, _ := ioutil.ReadFile("module.wasm")
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
// Compiles the module
module, err := wasmer.NewModule(store, wasmBytes)
if err != nil{
panic(err)
}
wasiEnv, _ := wasmer.NewWasiStateBuilder("wasi-program").
// Choose according to your actual situation
// Argument("--foo").
// Environment("ABC", "DEF").
// MapDirectory("./", ".").
Finalize()
// Instantiates the module
importObject, err := wasiEnv.GenerateImportObject(store, module)
if err != nil{
panic(err)
}
instance, err := wasmer.NewInstance(module, importObject)
if err != nil{
panic(err)
}
// Gets the `sum` exported function from the WebAssembly instance.
fib, _ := instance.Exports.GetFunction("fib")
// Calls that exported function with Go standard values. The WebAssembly
// types are inferred and values are casted automatically.
result, _ := fib(10000)
st := time.Now()
fmt.Println(result)
fmt.Println(time.Since(st).Seconds())
}
執(zhí)行
go run main.go
py調(diào)用
import pywasm
def fd_write(_: pywasm.Ctx):
return
vm = pywasm.load("./module.wasm", {'wasi_snapshot_preview1': {
'fd_write': fd_write
}})
result = vm.exec("fib", [10])
print(result)