FFI: using pointer as_ref/as_mut with opaque C structs

The C library I'm using exposes pointers to opaque structs, in memory it manages itself, which it provides when calling the C functions. If the pointer is not null, I can be sure it will outlive the current scope, so turning *mut T to Option<&'a mut T> using as_mut() seems like what I would want.

On the other hand, it comes with a number of conditions which give me a pause, since I have no visibility into what the C library is doing.

The question I have is, do I actually need to worry what it's doing? The struct is defined by bindgen as only containing _unused: [u8; 0] so aside from passing it back to C functions, I can't do anything with it from Rust. If it's zero-size as far as Rust is concerned, can any of those conditions even be false?

Then why don't you just leave it as a raw pointer? That would be the safest option.

Yes: the linked documentation specifically mentions that several requirements do apply even to ZSTs.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.