ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.97k stars 2.55k forks source link

Proposal: support auto coercing [*c] double pointers #8337

Open fengb opened 3 years ago

fengb commented 3 years ago

Translate-c functions often lead to signatures like args: [*c][*c]u8. Right now there's only a single level of coercion:

const single: [*][*c]u8 = args;      // this works
const better: [*][*:0]u8 = args;     // no bueno
const best: [*:null]?[*:0]u8 = args; // no bueno

This leads to a brute force approach via ptrCast:

const brute = @ptrCast(*:null]?[*:0]u8, args); // no sanity checks
CarwynNelson commented 3 years ago

New to the language, so I've partly been learning by looking for code examples on GitHub.

I have also come across this way to get around this problem

const vertexShaderSource: [:0]const u8 =
    \\#version 330 core
    \\layout (location = 0) in vec3 aPos;
    \\void main()
    \\{
    \\  gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
    \\}
;
const vertexSrcPtr: ?[*]const u8 = vertexShaderSource.ptr;
c.glShaderSource(vertexShader, 1, &vertexSrcPtr, null);

Which I found from https://github.com/cshenton/learnopengl/blob/805df1fc59918f352daedf41cc9b1214e5b80156/src/1_2_hello_triangle.zig

Edit: My original code that generated the error was:

const vertexShaderSource =
    \\#version 330 core
    \\layout (location = 0) in vec3 aPos;
    \\void main()
    \\{
    \\  gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
    \\}
;
c.glShaderSource(vertexShader, 1, &vertexShaderSource, null);
deckarep commented 3 years ago

I was recently bit by this: Since the docs state that you should never need to deal with [*c] form pointers (except from output of translate-c), it almost stands to reason that this is a bug or oversight.

I'm in the process of porting over a somewhat medium size C code base to Zig which makes use of double pointers so I'm having to utilize [c][c] in my arguments. It would be great if this was automatically coerced like the single pointer use case.

Of course, once I port everything over in Zig, I should be able to eradicate all [*c] usages completely.