zig
zig copied to clipboard
Language reference: Update WebAssembly example on how to export a function to the host
Zig Version
0.11.0-dev.1862+e7f128c20
Steps to Reproduce and Observed Behavior
Install above version of zig, and follow the exact steps in the WebAssembly documentation.
You will get:
$ node test.js
/Users/jim/dev/tmp/test-wasm-bug/test.js:10
add(1, 2);
^
TypeError: add is not a function
at /Users/jim/dev/tmp/test-wasm-bug/test.js:10:3
Node.js v19.5.0
This is because the built math.wasm is basically empty:
$ npm i wabt
$ npx wasm2wat math.wasm
(module
(memory (;0;) 16)
(global $__stack_pointer (mut i32) (i32.const 1048576))
(export "memory" (memory 0)))
I know this worked on a zig 0.10.x build.
Expected Behavior
The output shown in the documentation:
$ node test.js
The result is 3
So I got this to work with the following build.zig:
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding };
const optimize = b.standardOptimizeOption(.{ .preferred_optimize_mode = .ReleaseSmall });
const lib = b.addSharedLibrary(.{
.name = "math",
.root_source_file = .{ .path = "math.zig" },
.target = target,
.optimize = optimize,
});
lib.use_lld = false;
lib.rdynamic = true;
lib.install();
}
I then ran zig build instead of this command from the instructions:
zig build-lib math.zig -target wasm32-freestanding -dynamic
I then edited the test.js to reference "./zig-out/lib/math.wasm" instead.
I don't know why this works. I also don't know Zig. I'm trying it out as a way to author some specific WebAssembly.
This was changed in #14102. The language reference needs to be updated to reflect this change. The PR provides examples of how to export functions to the host environment. I've updated the issue's title to clarify this.
@Luukdegram thank you! I'll attempt a PR to update the example.