#how can i safely cast a `*const [N:0]u8` to `[]const u32`?

1 messages · Page 1 of 1 (latest)

pine vector
#

i need to do this because vulkan for some reason wants shader code as a [*:0]const u8

#

actually, it might not need to be null terminated since you pass in the size of the code too

worn ice
#

This is not really possible, since the alignment of u8 is smaller than the alignment of u32. How do you get the u8 pointer variable

pine vector
#

from @embedFile

#

the question should probably be []const u8 to [*:0]const u32, the shader code doesnt need to be null terminated (and cannot be)

#

how can i safely cast a []const u8 to [*:0]const u32?

worn ice
#

you can do

const aligned_data align(@alignOf(u32)) = @embedFile("file").*;

const u32_ptr: *const [@divExact(aligned_data.len, 4)]u32 = @ptrCast(&aligned_data);
worn ice
pine vector
worn ice
#

[N]u8, where N is the comptime known len of your shader file

pine vector
#

oh so then could i just pass in a slice for a function?

worn ice
#

afaik your function needs a u32 slice and not a aligned u8 slice

#

I don't know the complete vulkan function interface, but maybe @ptrCast(&aligned_data); is possible

pine vector
#

oh duh, youre right

#

oof seg fault

worn ice
pine vector
#
src\main.zig:524:62: error: TODO: implement @ptrCast between slices changing the length
        const vertex_shader_module = self.createShaderModule(@ptrCast(&vertex_shader_code));
                                                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

interesting error message

#

that vulkan binding might be doing other stuff

worn ice
#

then do @as(*const [@divExact(vertex_shader_code.len, 4)]u32, @ptrCast(&vertex_shader_code))

pine vector
#

did that, results in seg fault

worn ice
#

which os?

pine vector
#

windows

pine vector
#

how can i safely cast a *const [N:0]u8 to []const u32?

pine vector
#

bump

shrewd ivy
# pine vector bump

does this work?

const bytes: []const u8 = @embedFile("my_file");
const data: [@divExact(bytes.len, 4)]u32 = @bitCast(bytes[0..bytes.len].*);
_ = &data; // <- your `[]const u32`
pine vector
#

oh thats 8 bits off

#

so kinda close?

shrewd ivy
#

that's because you didn't do line 1

#

the type annotation is important

pine vector
#

oh i did see that

shrewd ivy
#

we need to rid of the sentinel terminator

pine vector
#

compiles, but is UB

shrewd ivy
#

UB how?

pine vector
#

seg fault

shrewd ivy
#

that's in a differnet part of your program then.

#

the whole calculation is done at compile time, no UB comes from there.

pine vector
#
If pCode is a pointer to SPIR-V code, pCode must adhere to the validation rules described by the Validation Rules within a Module section of the SPIR-V Environment appendix

hmm yeah this is what the validation layer says

pine vector
#

I FIGURED OUT THE PROBLEM

#

the length of the bytecode isn’t the same as the length of raw bytes I loaded

#

I needed the length of the file loaded