rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.75k stars 256 forks source link

Discuss the `WrapperStruct(UnsafeCell<some_c_struct>)`FFI pattern #385

Open tgross35 opened 1 year ago

tgross35 commented 1 year ago

Hey everyone,

I’d like to suggest adding the interior mutability FFI wrapper pattern to the FFI section, which usually looks something like this

#[repr(transparent)]
WrapperStruct(UnsafeCell<some_c_struct>)

This is used in e.g. the Linux kernel safe wrapper

I didn’t really understand it at first, but somebody explained it extremely well on Discord. Some of the explanation could likely be copied and pasted https://discord.com/channels/273534239310479360/818964227783262209/1040580112330002443

In general, I think the FFI section could use some updating, to be less of “this is how you call C functions” to more of “this is how you wrap a C API and make it safe”, since that’s what a lot of people are doing now as Rust works in to existing C projects. But that’s a big change, suitable for a separate issue.