Guarantee struct reload after being borrowed by C function


#1

I have a C function that takes a pointer to a Rust struct and may modify it. How can I guarantee that the next struct read after the C function reloads the value from memory instead of using registers or being optimized away.

Here is some code to illustrate:

let mut mystruct = MyStruct::new();
my_c_function(&mut mystruct as *mut _);

// i need the following read to be fresh from memory!
println!("The following value may have been modified by the C function: {}", mystruct.myfield);

#2

Does that not happen already?


#3

That works perfectly well.
If you pass the struct as a mutable pointer, Rust does that automatically (https://play.rust-lang.org/?gist=3cc2f72cdd69b83b21af28b82e1b09b5&version=stable&mode=release).


#4

It happens != It’s guaranteed.

I looked at the MIR output and I see that the storage for the struct (_10) is alive and not modified from its definition on line 7 until the end of the function. I’m no MIR expert but doesn’t that mean the compiler thinks the struct is untouched and may optimize or cache reads as it sees fit?


#5

The storage of the struct wouldn’t change - it’s never moved. It’s totally invalid for the compiler to assume that the data reachable through a mutable pointer to an opaque function hasn’t changed after the call.