Wasmer - 执行 WebAssembly 的 Go 库


MIT
跨平台
Google Go

软件简介

Wasmer 是一个 Go 库,用来执行 WebAssembly 二进制程序。

这里有一个示例程序 wasmer/test/testdata/examples/simple.rs, 使用 Rust 编写或者其他语言编译成
WebAssembly 的语言都行。

#[no_mangle]
pub extern fn sum(x: i32, y: i32) -> i32 {
    x + y
}

编译到 WebAssembly 后会生成
wasmer/test/testdata/examples/simple.wasm (Download
it
).

接下来就可以在 Go 语言中执行这个代码:

package main

import (
    "fmt"
    wasm "github.com/wasmerio/go-ext-wasm/wasmer"
)

func main() {
    // Reads the WebAssembly module as bytes.
    bytes, _ := wasm.ReadBytes("simple.wasm")

    // Instantiates the WebAssembly module.
    instance, _ := wasm.NewInstance(bytes)
    defer instance.Close()

    // Gets the `sum` exported function from the WebAssembly instance.
    sum := instance.Exports["sum"]

    // Calls that exported function with Go standard values. The WebAssembly
    // types are inferred and values are casted automatically.
    result, _ := sum(5, 37)

    fmt.Println(result) // 42!
}