我正在尝试使用wasm32-freestanding
目标将Zig函数编译为独立的WebAssembly模块。官方文档中有一节解释了如何做到这一点,但在最近版本的Zig(0.8.0(中,我在尝试用JavaScript实例化生成的模块时出错。
// file: main.zig
export fn add(a: i32, b: i32) i32 {
return a +% b;
}
// file: test.js
WebAssembly.instantiate((function() {
const source = require("fs").readFileSync("main.o");
return new Uint8Array(source);
})(), { env: {} }).then(wasm => {
const add = wasm.instance.exports.add;
console.log(add(1, 2));
});
$ zig version
0.8.0
$ node --version
14.17.3
$ zig build-obj main.zig -target wasm32-freestanding -dynamic -OReleaseFast
$ wc -c main.o # the generated code has extension `.o` instead of `.wasm`
135
$ node test.js
(node:2449) UnhandledPromiseRejectionWarning: LinkError: WebAssembly.instantiate(): Import #0 module="env" function="__linear_memory" error: memory import must be a WebAssembly.Memory object
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2449) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2449) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
检查生成的wasm模块表明,它试图从作用域env
导入一个名为__linear_memory
的值。当然,这是失败的,因为我没有提供这样的进口。然而,示例项目zig-wasm测试包括一个wasm模块(使用旧版本的zig编译(,该模块不包括这些导入。
我在这里做错了什么?我是否应该只是向模块提供__linear_memory
导出,即使它没有被使用?
您应该尝试使用build-lib
而不是build-obj
。