Hello.
In my application I have a struct, and I need to pass a pointer to the instance to a function (specifically it’s setting some callback in a C library).
The C library keeps that pointer around to use later when I trigger the callback.
I’d like to initialise the struct, pass the pointer to it to the c library, and then return the struct, without changing the memory location so the C library doesn’t break.
My understanding is that the following is broken, because the &b
passed into the C library refers to a stack location that’s invalid after return.
fn init() Foo {
const b = Foo{};
function_from_c_lib(&b);
return b;
}
fn main() void {
const d = init();
}
I have 2 questions (assuming everything above is correct).
-
is this behaviour defined somewhere in the language reference? I couldn’t find a “Semantically returned values are memcpy’d” mention.
-
What are typical ways people get around this? Is it just to change
init
to take a*Foo
and have the caller deal with creation (whether on their stack or on the heap)?
It’s how I think I would do it in C, but I just haven’t seen many zig libraries have to do this, so I was wondering if I was missing something.Or , can I force it to be semantically inlined with
inline fn
?
Thanks for any help.