编程学习网 > 编程语言 > go > WebAssembly增加Go语言绑定
2020
04-17

WebAssembly增加Go语言绑定



为提供更好的跨平台支持,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 在本地桌面端将会有不错的进展。对此你有什么看法?


扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取