go编译wasm与调用

2022-02-07  本文已影响0人  ArtioL
package main

func main() {
}

// 这里指定导出函数名 后面需要用到


//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

命令行执行编译

tinygo build -o ./module.wasm -target wasi .

module.wasm为导出的文件名

go 调用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())
}

执行

go run main.go
image.png

py调用

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)
上一篇 下一篇

猜你喜欢

热点阅读