Files
wazero/examples/allocation/zig
Takeshi Yoneda b63d4e6dcd Deletes namespace API (#1018)
Formerly, we introduced `wazero.Namespace` to help avoid module name or import conflicts while still sharing the runtime's compilation cache. Now that we've introduced `CompilationCache` `wazero.Namespace` is no longer necessary. By removing it, we reduce the conceptual load on end users as well internal complexity. Since most users don't use namespace, the change isn't very impactful.

Users who are only trying to avoid module name conflict can generate a name like below instead of using multiple runtimes:

```go
moduleName := fmt.Sprintf("%d", atomic.AddUint64(&m.instanceCounter, 1))
module, err := runtime.InstantiateModule(ctx, compiled, config.WithName(moduleName))
```

For `HostModuleBuilder` users, we no longer take `Namespace` as the last parameter of `Instantiate` method: 

```diff
 	// log to the console.
 	_, err := r.NewHostModuleBuilder("env").
 		NewFunctionBuilder().WithFunc(logString).Export("log").
-		Instantiate(ctx, r)
+		Instantiate(ctx)
 	if err != nil {
 		log.Panicln(err)
 	}
```


The following is an example diff a use of namespace can use to keep compilation cache while also ensuring their modules don't conflict:

```diff

 func useMultipleRuntimes(ctx context.Context, cache) {
-	r := wazero.NewRuntime(ctx)
+	cache := wazero.NewCompilationCache()
 
 	for i := 0; i < N; i++ {
-		// Create a new namespace to instantiate modules into.
-		ns := r.NewNamespace(ctx) // Note: this is closed when the Runtime is
+		r := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCompilationCache(cache))
 
 		// Instantiate a new "env" module which exports a stateful function.
 		_, err := r.NewHostModuleBuilder("env").
```

Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-01-10 14:11:46 +09:00
..
2022-08-11 16:31:06 +08:00
2023-01-10 14:11:46 +09:00

Zig allocation example

This example shows how to pass strings in and out of a Wasm function defined in Zig, built with zig build.

$ go run greet.go wazero
wasm >> Hello, wazero!
go >> Hello, wazero!

greet.zig does a few things of interest:

  • Uses @ptrToInt to change a Zig pointer to a numeric type
  • Uses [*]u8 as an argument to take a pointer and slices it to build back a string

The Zig code exports "malloc" and "free", which we use for that purpose.

Notes

This example uses @panic() rather than unreachable to handle errors since unreachable emits a call to panic only in Debug and ReleaseSafe mode. In ReleaseFast and ReleaseSmall mode, it would lead into undefined behavior.

If building wasm with a pre-release version of Zig 0.10.0, use -fstage1 to avoid bugs in the new compiler.