www.ziglang.org icon indicating copy to clipboard operation
www.ziglang.org copied to clipboard

Example of Zig+WebAssembly beyond hello world

Open jameshfisher opened this issue 2 years ago • 1 comments
trafficstars

I've built an example of Zig+WebAssembly that goes beyond the 2+2 "hello world" in the docs, and shows how to manage memory: https://github.com/jameshfisher/zig-wasm-beyond-hello-world

But I have a few questions.

  1. Does my use of std.heap.WasmAllocator look reasonable? I couldn't find any examples anywhere.
  2. In particular, what is ctx in that API? It seems to be ignored.
  3. I think something like this example would be useful in official Zig docs. Would you welcome a contribution? If so, where?
  4. Where is the source for https://ziglang.org/documentation/master on GitHub?

Note: I tried to ask the above in the recommended chat. But it just kept giving me this error "Cannot send to nick/channel":

Screen Shot 2023-03-06 at 16 47 18

jameshfisher avatar Mar 06 '23 16:03 jameshfisher

For allocation, you're not supposed to call .vtable methods. Instead, you should call thing.allocator() which returns a struct of type std.mem.Allocator and then use .create() / .destroy() / .alloc() / .free(). This will automatically set the context parameter and provide all the default allocation functions. The context parameter is ignored for WasmAllocator but used for other allocators like the GeneralPurposeAllocator and arena allocator because they have state they need to keep for allocation that's not handled by the OS.

const allocator = std.heap.WasmAllocator.allocator();
allocator.create(...);

https://zig.guide/standard-library/allocators ziglearn doesn't have a page on wasm specifically, but the GeneralPurposeAllocator does support wasm.

This github probably isn't the right place to ask zig questions. I'm not sure why the libera chat web interface is broken. The first discord mentioned here is pretty active: https://github.com/ziglang/zig/wiki/Community, and StackOverflow has people answering questions tagged zig too.

Documentation for the language is in the zig source code at doc/langref.html.in:

https://github.com/ziglang/zig/blob/master/doc/langref.html.in

pfgithub avatar Apr 19 '24 23:04 pfgithub