Accessing MaybeUninit

⚓ Rust    📅 2026-01-07    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Accessing MaybeUninit

I'm working on an ffi crate and need some advice in one key area.
My types usually look like this:

pub struct Wrapper {
    inner: Pin<Box<MaybeUninit<sys::c_struct>>>,
    init: bool,
}

Pin is used because it's an audio library and moves can lead to seg faults.
MaybeUninit is used because of how I initialize the c struct. It usually follows the same pattern:

pub fn new() -> Result<Wrapper> {
    let mut wrapper = Wrapper::new_uninit();
    let res = unsafe { sys::c_initializer_function(wrapper.maybe_uninit_mut_ptr())} // below
    // Check res for errors
    wrapper.set_init(); // set wrapper.init = true
    Ok(wrapper)
}

fn new_uninit() -> Wrapper {
    let mut inner = Box::pin(MaybeUninit::<sys::c_struct>::uninit());
    Wrapper { 
        inner,
        init: false,
    }
}

Now, I need 3 helpers to access the inner pointer.

Used to pass the unitialized ptr to c_initializer_function
fn maybe_uninit_mut_ptr(&mut self) -> *mut sys::c_struct {
    self.inner.as_mut_ptr()
}

And 2 other got getting a *const and a *mut after it's initialized.

fn assume_init_ptr(&self) -> *const sys::c_struct {
    debug_assert!(self.init, "Wrapper used before initialization.");
    unsafe { &self.inner.assume_init() as *const _ }
}

fn assume_init_mut_ptr(&mut self) -> *mut sys::c_struct {
    debug_assert!(self.init, "Wrapper used before initialization.");
    unsafe { self.inner.assume_init_mut() }
}

The main concern I have is with the last 2, if my helpers are sound. I am unsure of the difference between:
unsafe { &self.inner.assume_init() as *const _}
and simply and simply
self.inner.as_ptr()

Or between
unsafe { self.inner.assume_init_mut() }
and
self.inner.as_mut_ptr()

What are correct the ways I should access the pointers here?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed