I have a pointer to whatever, *const anyopaque
. I know that it points to a struct, and I have an offset of a field in this struct. What’s the proper way to get a pointer to field?
I can do
const field_ptr: *const anyopaque = @ptrFromInt(
@intFromPtr(value) + offset,
);
but that round-trips a pointer through integer, which, in general, can’t always work (eg, on CHERI), and have poor aliasing implications. Is there a more precise way to offset anyopaque?
No idea what the implications of this are wrt aliasing, but you could try using pointer arithmetic:
const field_ptr: *const anyopaque = @as([*]const u8, @ptrCast(value)) + offset;
2 Likes

I didn’t realize Zig supports pointer arithmetic for [*]
pointers, thanks!
It didn’t in the past, you’re not remembering something wrong, just an outdated truth :^)
Out of curiosity, why do you have an offset to the field, and not the knowledge of which field it is?
Context is Things Zig comptime Won't Do
I am building a print
function that can print any Zig type not via monomoprising for every type, but by working of *const anyopaque
and RTTI information, which includes field names&offsets