#Getting from C and to C : [*c][*c]const u8

1 messages · Page 1 of 1 (latest)

slim nebula
#

Hi there
I have a C function that generates a [*c][*c]const u8 list of C strings
(aka char const**)
I was thinking that maybe ArrayList([]const u8) would possibly be the best Zig type to hold that list, but I don't know how to convert from/to that type

I was thinking that maybe looping is the only way to do that? But that sounds wrong-ish to me
Any ideas or tips on how to achieve the conversion? I'm super lost

tiny lotus
#

you can safely ptrCast it to [*][*:0]const u8

#

if you want to get it into an arraylist, then you'll have to loop over it

#
for(the_ptr[0..the_ptr_len]) |item| {
    try array_list.append(std.mem.span(item));
}
slim nebula
#
    const Extensions = std.ArrayList([*:0]const u8);
    
    pub fn getExts (A :std.mem.Allocator) Extensions {
      var count :u32= 0;
      const exts = c.glfwGetRequiredInstanceExtensions(&count);
      var result = Extensions.init(A);
      for (exts[0..count]) | ext | { try result.append(std.mem.span(ext)); }
      return result;

      // for(the_ptr[0..the_ptr_len]) |item| {
      //     try array_list.append(std.mem.span(item));
      // }
    }
```For context, this is my sloppy progress
do I need to worry about the memory going out of scope if it is used inside a function?

**edit**: It seemed to work. Hope I'm not leaking memory or something 🤔
lament barn
#
  • appending to an arraylist allocates if the arraylist needs to grow, so you need to deinitialize the arraylist from wherever the getExts function is used to create it
  • std.mem.span will return a [:0]const u8 (nul-terminated byte slice) in your code, so Extensions should be a std.ArrayList([:0]const u8). slices are typically easier to work with than the raw pointer, this is good
  • since std.mem.span doesn't copy memory, if the result of glfwGetRequiredInstanceExtensions requires you to take ownership of the resulting memory or can be invalidated in some other way, you would need to copy or otherwise handle this result. based on the glfw docs you shouldn't have to worry about where this memory comes from or what to do with it
slim nebula