Can an FFI function modify a variable that wasn't declared mutable?

后端 未结 1 1609
不思量自难忘°
不思量自难忘° 2021-01-18 12:24
fn main() {
    let val = 0;
    unsafe { foo(&val) }
}

extern \"C\" {
    pub fn foo(val: *const u32);
}

Implementation in C:



        
1条回答
  •  醉梦人生
    2021-01-18 13:03

    I'd say undefined behavior:

    Mutating non-mutable data — that is, data reached through a shared reference or data owned by a let binding), unless that data is contained within an UnsafeCell.

    And this might include:

    • if you use val after the FFI-call it might ignore the writes you did (e.g. cached the value in a register or due to constant propagation)
    • segfault in FFI because the referenced memory might be read-only
    • the write from FFI might show up in seemingly unrelated locations because the compiler reused the memory and assumed it had a well-defined value
    • and worse :)

    0 讨论(0)
提交回复
热议问题