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 在本地桌面端将会有不错的进展。对此你有什么看法?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值