Is it safe to cast a pointer in the way mentioned in the title, then access it? I've had some trouble finding detailed information on the safety of pointer casts.
Update+answer
Sounds like casting to ()
and back, then dereferencing, is safe. Even type punning is safe because C's "strict aliasing" rule is not in Rust. (But keep in mind that struct layout is largely undefined!) Source: smart guys in this thread, links from quinedot, also Aria's blog says so and she knows a lot about Rust
Things I've seen so far (warning: long)
- Actually running my code that does this seems to work fine. Miri also thinks it's safe. Playground link
- However it also thinks that, if I have
struct Thing(u8)
, and cast from a*mut u32
to a*mut Thing
, then dereference, it's safe.This seems like it's supposed to be undefined behavior, maybe it's something Miri can't detect.Playground link - If I have
struct Thing(u64)
and try to cast between a*mut u32
and a*mut Thing
the compiler says "casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused". I don't even have to run Miri. Playground link - std::ptr is not very helpful for this.
- Rust Reference: pointer-to-pointer cast says that when casting
*mut T
to*mut U
that "IfT
andU
are both sized, the pointer is returned unchanged." - Rustonomicon FFI gives an example that suggests casting between a C struct pointer and a Rust pointer to an unrelated struct is safe.
Root problem
If this sounds like an XY problem, maybe it is. My goal is to create an internet simulator of sorts, that can dynamically load users' code, from a lib, to add Machines to this internet. Similarly to how some video games can load mods at runtime. Basically, a plugin system. The need for *mut ()
comes from allowing users to create "methods" for their machines:
/// Machine interface
#[no_mangle]
pub unsafe extern "C" fn allocate_machine(buf: *mut ()) {}
#[no_mangle]
pub unsafe extern "C" fn send(machine: *mut (), msg: u8) {}
the main code then calls these functions.