I built a binary dynamic library as zig build-lib -dynamic string_utils.zig
for the below code:
const std = @import("std");
pub fn joinStrings(firstname: []const u8, lastname: []const u8, buf: *[]u8) !void {
var stream = std.io.fixedBufferStream(buf.*);
var writer = stream.writer();
try writer.print("Hello, {s} {s}!", .{ firstname, lastname });
buf.* = stream.getWritten();
}
Then created the string.utls.h
file as:
void joinStrings(const char* firstname, const char* lastname, char** buf);
Then created my main.zig
file as below:
const std = @import("std");
const c = @cImport({
@cInclude("string_ptr.h");
});
pub fn main() !void {
var buf: [*c]u8 = undefined;
c.joinStrings("Hasan", "Yousef", &buf);
const len = // how to read the length of the buf for memory allocation //
const greetings = std.mem.sliceFromRaw(u8, buf[0..len]);
std.debug.print("Saved string: {s}\n", .{greetings});
}
To get the length of a C string, you can use the std.mem.len
function.