IT资讯 Wasmtime 为 WebAssembly 增加 Go 语言绑定

bill · 2020-04-15 11:00:05 · 热度: 13

为提供更好的跨平台支持,WebAssembly 正在积极推动其在本地桌面端的进展。与此同时,Wasmtime(WebAssembly runtime)近期为它增加了 Go 绑定功能,这意味着开发者可直接在 Go 应用程序中调用 WebAssembly 模块。

Wasmtime 提供了 JIT 风格的 WebAssembly runtime,这是一个属于字节码联盟的项目,此前已为 Rust, C, Python 和 Microsoft .NET 提供了绑定,Go 语言则是其最新绑定的语言。

wasmtime-go 的代码已开源,下面介绍一个使用 wasmtime-go 编写 "Hello, world!" 的代码示例:

package main

import (
    "fmt"
    "github.com/bytecodealliance/wasmtime-go"
)

func main() {
    // Almost all operations in wasmtime require a contextual `store`
    // argument to share, so create that first
    store := wasmtime.NewStore(wasmtime.NewEngine())

    // Compiling modules requires WebAssembly binary input, but the wasmtime
    // package also supports converting the WebAssembly text format to the
    // binary format.
    wasm, err := wasmtime.Wat2Wasm(`
      (module
        (import "" "hello" (func $hello))
        (func (export "run")
          (call $hello))
      )
    `)
    check(err)

    // Once we have our binary `wasm` we can compile that into a `*Module`
    // which represents compiled JIT code.
    module, err := wasmtime.NewModule(store, wasm)
    check(err)

    // Our `hello.wat` file imports one item, so we create that function
    // here.
    item := wasmtime.WrapFunc(store, func() {
        fmt.Println("Hello from Go!")
    })

    // Next up we instantiate a module which is where we link in all our
    // imports. We've got one improt so we pass that in here.
    instance, err := wasmtime.NewInstance(module, []*wasmtime.Extern{item.AsExtern()})
    check(err)

    // After we've instantiated we can lookup our `run` function and call
    // it.
    run := instance.GetExport("run").Func()
    _, err = run.Call()
    check(err)
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

此功能会在即将发布的 Wasmtime 0.16.0 milestone 版本中提供,0.16 版本还增加了 .NET 绑定功能,以及其他有趣的变更。

字节码联盟力推的 WebAssembly 接口类型增加了 WebAssembly 与其他语言的互通性。Mozilla 表示,WebAssembly 接口类型简化了应用程序与 WebAssembly 模块间来回传递复杂类型所需的“胶水代码”。

按照目前的进度,相信今年 Wasmtime 和 WebAssembly 在本地桌面端将会有不错的进展。对此你有什么看法?

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册