Guarantee struct reload after being borrowed by C function

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);
1 Like

Does that not happen already?

1 Like

That works perfectly well.
If you pass the struct as a mutable pointer, Rust does that automatically (Rust Playground).

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?

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.

1 Like