Skip to content

References and pointers #49

@mversic

Description

@mversic

I'd like to find how safe it is to use references in FFI but only as input arguments to extern C functions. Here is the section describing it.

I'm interested in situation where references are provided from Rust code to extern C functions, specifically:
foo.rs

extern fn fun(arg: &u32);

fn main() {
    let x: u32 = 4;
    unsafe {
        fun(&x);
    }
} 

foo.c

void fun(*int arg) {
    int x = *arg;
    // do something with x
    // what if arg is mutated?
}

extern fun cannot be called from rust with null values. If C function documents that doesn't accept null values this is acceptable. If it is required to be nullable, it can be wrapped in Option.

what if x is mutated inside fun? This seems like a safety issue, maybe an undefined behavior, data corruption or data race. It seems to me that using references is inherently unsafe when interfacing with C code. If that is so, should this section be modified to always advise against use of references in FFI?

what about mutable references &mut? Would it be safe to use those in FFI? Are there possibly some lifetime related issues?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions