...

Text file src/github.com/tetratelabs/wazero/examples/import-go/README.md

Documentation: github.com/tetratelabs/wazero/examples/import-go

     1## Import go func example
     2
     3This example shows how to define, import and call a Go-defined function from a WebAssembly-defined function.
     4
     5If the current year is 2022, and we give the argument 2000, [age-calculator.go](age-calculator.go) should output 22.
     6```bash
     7$ go run age-calculator.go 2000
     8println >> 21
     9log_i32 >> 21
    10```
    11
    12### Background
    13
    14WebAssembly has neither a mechanism to get the current year, nor one to print to the console, so we define these in Go.
    15Similar to Go, WebAssembly functions are namespaced, into modules instead of packages. Just like Go, only exported
    16functions can be imported into another module. What you'll learn in [age-calculator.go](age-calculator.go), is how to
    17export functions using [HostModuleBuilder](https://pkg.go.dev/github.com/tetratelabs/wazero#HostModuleBuilder) and how a
    18WebAssembly module defined in its [text format](https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#text-format%E2%91%A0)
    19imports it. This only uses the text format for demonstration purposes, to show you what's going on. It is likely, you
    20will use another language to compile a Wasm (WebAssembly Module) binary, such as TinyGo. Regardless of how wasm is
    21produced, the export/import mechanics are the same!
    22
    23### Where next?
    24
    25The following examples continue the path of learning about importing and exporting functions with wazero:
    26
    27#### [WebAssembly System Interface (WASI)](../../imports/wasi_snapshot_preview1/example)
    28
    29This uses an ad-hoc Go-defined function to print to the console. There is an emerging specification to standardize
    30system calls (similar to Go's [x/sys](https://pkg.go.dev/golang.org/x/sys/unix)) called WebAssembly System Interface
    31[(WASI)](https://github.com/WebAssembly/WASI). While this is not yet a W3C standard, wazero includes a
    32[wasi package](https://pkg.go.dev/github.com/tetratelabs/wazero/wasi).

View as plain text