Skip to content

Conversation

paokitore
Copy link

@paokitore paokitore commented Jul 22, 2025

This fixes #24513 and another issue I noticed: casting const void* to int* did not work.

Both of those issues are fixed with translate-c, so this PR might be useless though.

examples:

void *g = (void*)f;

used to translate to:

var g: ?*anyopaque = @as(?*anyopaque, @ptrCast(f));

forgetting a @constCast.

and

const void *c;
int *d = (int*)c;

the second line used to translate to:

var d: [*c]c_int = @as([*c]c_int, @ptrCast(@volatileCast(@constCast(c))));

forgetting a @alignCast.

@alexrp
Copy link
Member

alexrp commented Jul 22, 2025

This would effectively be made obsolete by #24497, so I think we'd only consider taking this PR if #24497 for some reason fails to land in 0.15.0.

@paokitore
Copy link
Author

paokitore commented Aug 3, 2025

The previous CI failed with 3 errors and the next one will still fail with 2 errors:

  1. Formatting: I forgot and the last commit fixed it.

For the other two, I'd say that it's more of the tests' fault.

expected:

var func_ptr: ?*anyopaque = @as(?*anyopaque, @ptrCast(&foo));

got:

var func_ptr: ?*anyopaque = @as(?*anyopaque, @ptrCast(@volatileCast(@constCast(&foo))));

This fail is quite weird because the code expected by the test actually does not compile :

test1.zig:3:50: error: @ptrCast discards const qualifier
    var func_ptr: ?*anyopaque = @as(?*anyopaque, @ptrCast(&foo));
                                                 ^~~~~~~~~~~~~~
test1.zig:3:50: note: use @constCast to discard const qualifier

So I would say that this is an issue with the test.

expected:

@as([*c]c_int, @ptrCast(@volatileCast(@constCast(a))))

got:

@as([*c]c_int, @ptrCast(@volatileCast(@constCast(@alignCast(a)))))

I just have an extra @alignCast which still outputs valid zig code.
I don't think this in an issue, because there are many cases where an extra @alignCast is outputted:

typedef struct {
  int a;
} A;
void main() {
  int a = 3;
  int *a_ptr = &a;
  A *aa_ptr = (A*)a_ptr;
}

gets translated to

pub const A = extern struct {
    a: c_int = @import("std").mem.zeroes(c_int),
};
pub export fn main() void {
    var a: c_int = 3;
    _ = &a;
    var a_ptr: [*c]c_int = &a;
    _ = &a_ptr;
    var aa_ptr: [*c]A = @as([*c]A, @ptrCast(@alignCast(a_ptr)));
    _ = &aa_ptr;
}

even though c_int and A have the same alignment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

translate-c: cast function pointer to void pointer
2 participants