| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
_ "embed" |
| 6 |
"fmt" |
| 7 |
"log" |
| 8 |
"os" |
| 9 |
|
| 10 |
"github.com/tetratelabs/wazero" |
| 11 |
"github.com/tetratelabs/wazero/api" |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
var counterWasm []byte |
| 20 |
|
| 21 |
|
| 22 |
func main() { |
| 23 |
|
| 24 |
ctx := context.Background() |
| 25 |
|
| 26 |
|
| 27 |
cacheDir, err := os.MkdirTemp("", "example") |
| 28 |
if err != nil { |
| 29 |
log.Panicln(err) |
| 30 |
} |
| 31 |
defer os.RemoveAll(cacheDir) |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
cache, err := wazero.NewCompilationCacheWithDir(cacheDir) |
| 36 |
if err != nil { |
| 37 |
log.Panicln(err) |
| 38 |
} |
| 39 |
defer cache.Close(ctx) |
| 40 |
|
| 41 |
|
| 42 |
runtimeConfig := wazero.NewRuntimeConfig().WithCompilationCache(cache) |
| 43 |
|
| 44 |
|
| 45 |
runtimeFoo := wazero.NewRuntimeWithConfig(ctx, runtimeConfig) |
| 46 |
runtimeBar := wazero.NewRuntimeWithConfig(ctx, runtimeConfig) |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
m1 := instantiateWithEnv(ctx, runtimeFoo) |
| 51 |
m2 := instantiateWithEnv(ctx, runtimeBar) |
| 52 |
|
| 53 |
for i := 0; i < 2; i++ { |
| 54 |
fmt.Printf("m1 counter=%d\n", counterGet(ctx, m1)) |
| 55 |
fmt.Printf("m2 counter=%d\n", counterGet(ctx, m2)) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
func counterGet(ctx context.Context, mod api.Module) uint64 { |
| 61 |
results, err := mod.ExportedFunction("get").Call(ctx) |
| 62 |
if err != nil { |
| 63 |
log.Panicln(err) |
| 64 |
} |
| 65 |
return results[0] |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
type counter struct { |
| 70 |
counter uint32 |
| 71 |
} |
| 72 |
|
| 73 |
func (e *counter) getAndIncrement() (ret uint32) { |
| 74 |
ret = e.counter |
| 75 |
e.counter++ |
| 76 |
return |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
func instantiateWithEnv(ctx context.Context, r wazero.Runtime) api.Module { |
| 81 |
|
| 82 |
c := &counter{} |
| 83 |
_, err := r.NewHostModuleBuilder("env"). |
| 84 |
NewFunctionBuilder().WithFunc(c.getAndIncrement).Export("next_i32"). |
| 85 |
Instantiate(ctx) |
| 86 |
if err != nil { |
| 87 |
log.Panicln(err) |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
mod, err := r.Instantiate(ctx, counterWasm) |
| 92 |
if err != nil { |
| 93 |
log.Panicln(err) |
| 94 |
} |
| 95 |
return mod |
| 96 |
} |