I have no experience with system level programming at all. I am trying to get a wasm platform by try an error.
I have something that works, but I have a question about it. Here is the exported zig function:
export fn allocUint8(length: u32) [*]u8 {
const slice = std.heap.page_allocator.alloc(u8, length) catch
@panic("failed to allocate memory");
return slice.ptr;
}
const RocList = struct { pointer: [*]u8, length: usize, capacity: usize };
extern fn roc__handlerForHost_1_exposed(*RocList, *RocList) void;
export fn run_roc(input: [*]u8, input_len: usize) [*]const u8 {
defer std.heap.page_allocator.free(input[0..input_len]);
var arg = RocList{ .pointer = input, .length = input_len, .capacity = input_len };
// TODO: What should the pointer be for the empty callresult?
// Is this on the stack or the heap? Do I have to deallocate?
var callresult = RocList{ .pointer = input, .length = 0, .capacity = 0 };
roc__handlerForHost_1_exposed(&callresult, &arg);
return callresult.pointer;
}
First the wasm runtime calls allocUint8
to allocate some memory. Then it calls run_roc
to run the roc code. The defer statement at the beginning makes sure, that the allocated memory gets freed (I hope).
But what about callresult
? Roc writes a list of [*]u8 somewhere in the memory.I think, that it is on the heap. So do I have to free it? Can I do this in this function or has the wasm runtime call a free function afterwards?
Also, what should callback.pointer be initialized with? Currently, I use the input-pointer. But this seems like an hack.
I know, this is more a zig question. But maybe you can help me anyway?
Technically speaking, callresult
shouldn't be initialized at all.
roc__handlerForHost_1_exposed
just needs some stack space to write output data to
So do I have to free it?
yeah, call result should get freed, but isn't currently. Obviously it would have to be freed by the caller of run_roc
, or it would need to be converted into a data structure with a different memory management plan such that it can be freed automatically.
Do you have a link to the full code, I just want some more info about use and surrounding code.
Here is the current status of my experiment: https://github.com/ostcar/goroc
Last updated: Jul 06 2025 at 12:14 UTC