Created
February 18, 2023 12:48
-
-
Save salrashid123/02940fc66c49f323aa25cd52d4407ae6 to your computer and use it in GitHub Desktop.
Load and run wasm in go with wasmer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
$ cat helloworld.ts | |
export function add(a: i32, b: i32): i32 { | |
return a + b; | |
} | |
$ npm install -g assemblyscript | |
$ asc helloworld.ts -o hello-world.wasm | |
$ go run main.go | |
*/ | |
import ( | |
"fmt" | |
"io/ioutil" | |
wasmer "github.com/wasmerio/wasmer-go/wasmer" | |
) | |
func main() { | |
// use TEE attestation token here to download `hello-world.wasm` | |
wasmBytes, err := ioutil.ReadFile("hello-world.wasm") | |
if err != nil { | |
panic(err) | |
} | |
engine := wasmer.NewEngine() | |
store := wasmer.NewStore(engine) | |
// Compiles the module | |
module, err := wasmer.NewModule(store, wasmBytes) | |
if err != nil { | |
panic(err) | |
} | |
// Instantiates the module | |
importObject := wasmer.NewImportObject() | |
instance, err := wasmer.NewInstance(module, importObject) | |
if err != nil { | |
panic(err) | |
} | |
// Gets the `add` exported function from the WebAssembly instance. | |
add, err := instance.Exports.GetFunction("add") | |
if err != nil { | |
panic(err) | |
} | |
// Calls that exported function with Go standard values. The WebAssembly | |
// types are inferred and values are casted automatically. | |
result, err := add(1, 5) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment