How do I extract an initialized field from an uninitialized struct

⚓ Rust    📅 2026-06-02    👤 surdeus    👁️ 1      

surdeus

I'm wrapping some C code, and the way the API works, sometimes only part of the struct is initialized (we are given a pointer to the data which we do not own). IIUC, this means I cannot create a reference to the struct in Rust: I need to somehow create a reference directly to the fields in question. How do I do this?

My current approach is something like the following (playground)

use std::ffi::c_void;


// imagine this struct
pub struct Foo;

#[repr(C)]
struct CData {
    foo: Foo, // uninit
    bar: u8,
}

// to get the data in cdata.bar without creating in uninit ref to foo, imagine the following fn:
extern "C" fn get_data() -> *mut c_void {
    // implementation for example's sake
    let x = Box::<CData>::new_uninit();
    let raw = Box::into_raw(x) as *mut CData;
    unsafe { (&raw mut (*raw).bar).write(42) };
    raw as *mut c_void
}

// in my code I do
pub fn get_data_wrapped() -> u8 {
    unsafe { 
        let data = get_data() as *mut CData;
        let field = &raw const (*data).bar;
        *field
    }
}

but I'm worried I'm dereferencing the pointer of not fully init data - meaning I'm breaking Rust rules.

6 posts - 6 participants

Read full topic

🏷️ Rust_feed