#Possible to convert to/from struct and string?

1 messages · Page 1 of 1 (latest)

abstract jacinth
#

I'm a noob at zig, but I'm just thinking if it's possible to take the raw bytes of a struct and convert it to a []u8? And back.

gaunt veldt
#

std.mem.asBytes should work for the conversion to raw bytes

abstract jacinth
#

i'm guessing stuff like arrays would be problematic in the struct to convert back? Or at least in like c the string is a char* which is just an address, no?

gaunt veldt
#

to be clear, std.mem.asBytes just lets you see the bytes

#

if you really wanna do the cast yourself it could look something like this:

    var s = S{ .a = 0 };

    const slice: []u8 = @as(*[@sizeOf(@TypeOf(s))]u8, @ptrCast(&s));

    std.debug.print("{d}\n", .{s.a});
    slice[0] = 1;
    std.debug.print("{d}\n", .{s.a});
````S` could really be anything here

ill leave it to you to figure out how to do the inverse
abstract jacinth
#

awesome

astral radish
#

slice is just the bytes of the struct -- the bytes that make up the S in memory.