This project demonstrates how to use Wasmtime with Go to pass arguments between the Go runtime and a WebAssembly (Wasm) module, which is defined using WebAssembly Text Format (WAT). The example showcases how you can pass strings from Go to a WebAssembly function, and have them printed using a host-defined function.
- Go 1.16 or later installed
- Wasmtime Go package installed
You can install the Wasmtime Go package using:
go get github.com/bytecodealliance/wasmtime-go
main.go
: The main program that sets up the Wasm environment, passes arguments from Go to Wasm, and prints them using a Wasm-hosted function.
- Argument Passing: Demonstrates how to pass string arguments from Go to Wasm.
- WAT to Wasm Compilation: Shows how to compile WAT (WebAssembly Text Format) to Wasm bytes.
- Function Import/Export: Includes a host function that is imported into the Wasm module, and a Wasm function that is called from Go.
-
Wasmtime Setup:
- Create a new engine and store for managing Wasm execution.
- Compile WAT into Wasm bytes and then create a Wasm module.
-
Function Import:
- Define an
env.print_string
function in Go which is hooked to print strings passed from Wasm.
- Define an
-
Memory Management:
- Allocate memory in Wasm and manipulate it directly from Go to write strings.
-
Wasm Function Invocation:
- Call an exported Wasm function with a string's memory location and length to trigger the host-defined
print_string
.
- Call an exported Wasm function with a string's memory location and length to trigger the host-defined
-
Example Execution:
- Test the setup by passing a series of strings from Go to the Wasm module, printing each using the defined function.
-
Clone this repository:
git clone <repository-url> cd wasm-with-go-wasmtime
-
Execute the example:
go run main.go
-
The output should display:
Wasm says: Hello from Go! Wasm says: This is a test Wasm says: WebAssembly is cool!
This project is open source and available under the MIT License.
This tutorial should serve as a basic guide to building more advanced WebAssembly applications using Wasmtime and Go. Feel free to expand on this example by exploring more complex data types, error handling, and interacting with other WebAssembly modules.