ZigEmbeddedGroup / microzig

Unified abstraction layer and HAL for several microcontrollers
zlib License
1.26k stars 102 forks source link

Please help: with format a string with numbers or allocator instance in microzig. #132

Open kanstantsin-bucha opened 1 year ago

kanstantsin-bucha commented 1 year ago

Hello! Thank you for your work on that project.

I start to use it in development. I want to write some simple apps to understand if it works.

I want to be able to format a string with numbers.

I need help with the allocator issue. I need help finding a way to use the standard library functions that require an allocator instance.

Example:

  const allocator = os.heap.page_allocator;

   const string1 = try std.fmt.allocPrint(allocator, "{d}", .{count()});
   defer allocator.free(string1);
   microzig.hal.uart.write(0, string1);

Gives me the error:

 error: root struct of file 'start' has no member named 'os'
 root.os.heap.page_allocator

Is there a way to get the allocator in the Microzig? or ESP32C2 environment? Can I resolve those issues without the allocator usage? Thank you in advance.

r4gus commented 1 year ago

Hi sorry for the late reply. For embedded projects you have to setup an allocator yourself. The easiest way you can do that is to use a fixed buffer allocator.

var buffer: [4096]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(buffer[0..]);
const allocator = fba.allocator();

For the example above keep in mind that you can't free the memory allocated from a FBA, i.e., you have to place it strategically in your code.

If you have any questions regarding Microzig and embedded programming in Zig, the best place to go is the Zig Embedded Group Discord server (https://discord.gg/XRbsd3Ee). The response time is usually pretty quick.