I'm working on my first zig program, and it uses a mixture of zig and C.
I have a C function of the form:
int generate_array(MyType** ptr);
It creates an array of MyType, assigns the provided pointer to point to it and returns the size of the array.
After some playing around with a simple case (using typedef int MyType) I found the following zig code worked:
var ptr: [*c]c_int = null;
const sz = cMyCFile.generate_array(&ptr);
defer {
// Free the allocated memory
if (ptr != null) {
c.free(ptr);
}
}
try stdout.print("generated array size {d}\n", .{sz});
for (0..@intCast(sz)) |i| {
var new_int: c_int = ptr[i];
try stdout.print(" {d}\n", .{new_int});
}
While trying to find this I came across c-pointers: https://zig.guide/working-with-c/c-pointers
Outside of automatically translated C code, the usage of [*c] is almost always a bad idea, and should almost never be used.
But my zig code is not automatically translated from C (though I'm guessing my C code counts as automatically translated code in this context), so would there be anyway for me to do the above without using a[*c]?
Have I taken the right approach here? This is just a warm-up to the real problem which involves much more complicated C types, and I basically want to write a function to copy the data into zig native types
Up until now, we have used the following kinds of pointers: