#Cast `?*const anyopaque` to []const u8

1 messages · Page 1 of 1 (latest)

surreal current
#

I'm trying to parse a struct at comptime. Some of the fields will be set as a []const u8 with a default value. How do I go about casting the default_value into a []const u8?

const foo = struct {
    comptime description: []const u8 = "Some description",
};

fn parseStruct(comptime T: type) []const u8 {
    // I will be parsing the other fields but not important for question
    const field = @typeInfo(T).Struct.fields[0];
    if (field.type == []const u8) {
        const should_be_a_string: *const anyopaque = field.default_value orelse "";
        return should_be_a_string;
    } else {
        return "";
    }
}

fn main() void {
    std.debug.print("{s}", .{parseStruct(foo)})
}
covert sleet
#

the default_value field in the field info is actually a juts a type-erased pointer to the default value

#

in order to get the default value, you should do @ptrCast(*align(1) const field.type, field.default_value orelse <handle null case however you want>).*

#

so in your case, const should_be_a_string: []const u8 = if (field.default_value) |ptr| @ptrCast(*align(1) const []const u8, ptr).* else "";

surreal current
#

I'm not that comfortable with alignment but wouldn't it have to be the alignment of field.type in the general case, not align(1)?

#

(but thanks it does solve my original question)

covert sleet
#

and plus, it's just easier

#

because if you want to cast it to *const []const u8, you'd have to do @ptrCast(*const []const u8, @alignCast(@alignOf([]const u8), ptr))

#

and just as a note: any pointer with any alignment can be annotated with align(1) safely