expression
Typed opaque handles
A handle points to an object whose layout is hidden from the consumer. Use distinct pointer types for distinct foreign objects, never instantiate or dereference a placeholder type. The example uses an actual Rust-owned value only to demonstrate a pointer round trip. The foreign placeholder provides no layout guarantee. Expected stdout (not executed): 12 Common mistake: Reading memory through the placeholder or using a placeholder value as the real C object.
Formal Syntax & Structure
rust syntaxrust
#[repr(C)] struct ForeignHandle { /* private fields */ }Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::marker::{PhantomData, PhantomPinned}; #[repr(C)] struct ForeignHandle { _private: [u8; 0], _marker: PhantomData<(*mut u8, PhantomPinned)> } let mut value = 12_u32; let ptr = (&mut value as *mut u32).cast::<ForeignHandle>(); // SAFETY: the original u32 remains live; the opaque pointer was never dereferenced. let restored = unsafe { *ptr.cast::<u32>() }; println!("{restored}");}