Hi everyone!
Here’s what I am trying to do, with the latest Zig nightly build.
I have an array of values rgba
that is generated in JavaScript, and want to process it in Zig.
That works perfectly.
However, in Zig, I have an array of values nums
that I can’t access anymore once once I set the array
to contain the rgba
values.
When I try to access the nums
array, I get only negative values (all -1).
At first, I thought it was because I didn’t have enough memory, so I increased using the grow()
method, but that didn’t help.
The funny thing is that, I am not even reading the array
in Zig, and if I change its size from 640 * 480 * 4
to 640 * 480 * 3
, everything works.
Here’s all the code, using a minimal example. I would really appreciate it if you could point out what I am doing wrong. Thank you in advance!
main.zig
:
extern fn print(val: i32) void;
const nums = [_]i32{ 291, 409, 270, 269, 267, 0, 37, 39, 40, 185, 61, 146, 91, 181, 84, 17, 314, 405, 321, 375 };
export fn iterate() void {
print(nums.len);
for (nums, 0..) |val, i| {
print(@intCast(i));
print(val);
}
}
index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" http-equiv="X-UA-Compatible" content="chrome=1">
<script>
function setup() {
const imports = {
env: {
print: function(x) { console.log(x); }
}
};
return WebAssembly.instantiateStreaming(fetch("zig-out/lib/main.wasm"), imports).then((result) => {
return result.instance.exports;
});
}
setup().then((wasm) => {
wasm.memory.grow(4096);
// changing this size to 640 * 480 * 3 makes it work.
const size = 640 * 480 * 4;
var rgba = new Uint8Array(size);
for (let i = 0; i < size; ++i) {
rgba[i] = 255;
}
var array = new Uint8Array(wasm.memory.buffer, 0, size);
// this line breaks the `wasm.iterate()` function, commenting it out works.
array.set(rgba);
console.log(array);
wasm.iterate();
});
</script>
</head>
</html>
build.zig
:
const std = @import("std");
pub fn build(b: *std.Build) void {
const lib = b.addSharedLibrary(.{
.name = "main",
.root_source_file = .{ .path = "main.zig" },
.optimize = .Debug,
.target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding },
.use_llvm = false,
.use_lld = false,
});
// export all functions marked with "export"
lib.rdynamic = true;
b.installArtifact(lib);
}