If I'm writing a zig library, how do I return an allocated byte array and free it later?
Returning a pointer to a null-terminated allocated byte array is straight-forward:
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
export fn allocByteArrayZ(size: u8) [*]u8 {
const arrayZ = gpa.allocator().alloc(u8, size) catch unreachable;
arrayZ[size - 1] = 0;
return arrayZ.ptr;
}
But I'm stuck on how to convert the pointer back into a slice so I can free it later.
export fn freeByteArrayZ(arrayZ: [*]u8) void {
gpa.allocator().free(arrayZ); // doesn't work, expects a []u8
}
I know the length, as I can assume it is a null-terminated array:
const array = @ptrCast([*:0]u8, arrayZ);
But I don't know how to turn [*:0]u8 into []u8