#Possible to convert to/from struct and string?
1 messages · Page 1 of 1 (latest)
std.mem.asBytes should work for the conversion to raw bytes
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?
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
awesome
Arrays would be fine because they're value types (they contain their elements, rather than pointing to them), however slices, or indeed any pointer type, may be an issue for you.
slice is just the bytes of the struct -- the bytes that make up the S in memory.
S in mem?