Skip to content

Instantly share code, notes, and snippets.

@Hywan
Last active May 28, 2019 14:13
Show Gist options
  • Save Hywan/83d06597ce2888ad953371803c918fa4 to your computer and use it in GitHub Desktop.
Save Hywan/83d06597ce2888ad953371803c918fa4 to your computer and use it in GitHub Desktop.
Go Wasm example, import.go
package main
// // 1️⃣ Declare the `sum` function signature (see cgo).
//
// #include <stdlib.h>
//
// extern int32_t sum(void *context, int32_t x, int32_t y);
import "C"
import (
"fmt"
wasm "github.com/wasmerio/go-ext-wasm/wasmer"
"unsafe"
)
// 2️⃣ Write the implementation of the `sum` function, and export it (for cgo).
//export sum
func sum(context unsafe.Pointer, x int32, y int32) int32 {
return x + y
}
func main() {
// Reads the WebAssembly module as bytes.
bytes, _ := wasm.ReadBytes("import.wasm")
// 3️⃣ Declares the imported functions for WebAssembly.
imports, _ := wasm.NewImports().Append("sum", sum, C.sum)
// 4️⃣ Instantiates the WebAssembly module with imports.
instance, _ := wasm.NewInstanceWithImports(bytes, imports)
// Close the WebAssembly instance later.
defer instance.Close()
// Gets the `add1` exported function from the WebAssembly instance.
add1 := instance.Exports["add1"]
// Calls that exported function.
result, _ := add1(1, 2)
fmt.Println(result)
// add1(1, 2)
// = sum(1 + 2) + 1
// = 1 + 2 + 1
// = 4
// QED
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment