|
| 1 | +const std = @import("std"); |
| 2 | +const wasmer = @import("wasmer"); |
| 3 | +const assert = std.debug.assert; |
| 4 | + |
| 5 | +var gpa = std.heap.GeneralPurposeAllocator(.{}){}; |
| 6 | +const allocator = gpa.allocator(); |
| 7 | + |
| 8 | +const wat = |
| 9 | + \\(module |
| 10 | + \\ (func $host_function (import "" "host_function")) |
| 11 | + \\ ;; (global $host_global (import "env" "host_global") i32) |
| 12 | + \\ (func $function (export "guest_function") (result i32) (global.get $global)) |
| 13 | + \\ (global $global (export "guest_global") i32 (i32.const 42)) |
| 14 | + \\ (table $table (export "guest_table") 1 1 funcref) |
| 15 | + \\ (memory $memory (export "guest_memory") 1) |
| 16 | + \\) |
| 17 | +; |
| 18 | + |
| 19 | +fn host_func_callback() void { |
| 20 | + std.log.info("Calling back...\n> ", .{}); |
| 21 | +} |
| 22 | + |
| 23 | +pub fn main() !void { |
| 24 | + run() catch |err| { |
| 25 | + const err_msg = try wasmer.lastError(std.heap.c_allocator); |
| 26 | + defer std.heap.c_allocator.free(err_msg); |
| 27 | + |
| 28 | + std.log.err("{s}", .{err_msg}); |
| 29 | + |
| 30 | + return err; |
| 31 | + }; |
| 32 | +} |
| 33 | + |
| 34 | +pub fn run() !void { |
| 35 | + var wasm_bytes = try wasmer.watToWasm(wat); |
| 36 | + defer wasm_bytes.deinit(); |
| 37 | + |
| 38 | + std.log.info("creating the store...", .{}); |
| 39 | + |
| 40 | + const engine = try wasmer.Engine.init(); |
| 41 | + defer engine.deinit(); |
| 42 | + const store = try wasmer.Store.init(engine); |
| 43 | + defer store.deinit(); |
| 44 | + |
| 45 | + std.log.info("compiling module...", .{}); |
| 46 | + |
| 47 | + const module = try wasmer.Module.init(store, wasm_bytes.toSlice()); |
| 48 | + defer module.deinit(); |
| 49 | + |
| 50 | + std.log.info("creating the imported function...", .{}); |
| 51 | + |
| 52 | + const host_func = try wasmer.Func.init(store, host_func_callback); |
| 53 | + // defer host_func.deinit(); |
| 54 | + |
| 55 | + // std.log.info("Creating the imported global...", .{}); |
| 56 | + |
| 57 | + std.log.info("instantiating module...", .{}); |
| 58 | + |
| 59 | + const instance = try wasmer.Instance.init(store, module, &.{host_func}); |
| 60 | + defer instance.deinit(); |
| 61 | + |
| 62 | + std.log.info("retrieving exports...", .{}); |
| 63 | + |
| 64 | + const guest_function = instance.getExportFunc(module, "guest_function") orelse { |
| 65 | + std.log.err("failed to retrieve \"guest_function\" export from instance", .{}); |
| 66 | + return error.ExportNotFound; |
| 67 | + }; |
| 68 | + defer guest_function.deinit(); |
| 69 | + |
| 70 | + const memory = instance.getExportMem(module, "guest_memory") orelse { |
| 71 | + std.log.err("failed to retrieve \"guest_memory\" export from instance", .{}); |
| 72 | + return error.ExportNotFound; |
| 73 | + }; |
| 74 | + defer memory.deinit(); |
| 75 | +} |
0 commit comments