1

I can expose a C function to Rust code via the FFI as follows:

use std::os::raw::c_int;

mod c {
    #[link(name="...")]
    extern "C" {
        pub fn add(a: c_int, b: c_int) -> c_int;
    }
}

pub fn add(a: c_int, b: c_int) -> c_int {
    unsafe {
        c::add(a, b)
    }
}

Now I can call add from Rust without having to wrap it in another unsafe block. But what if I want to do the same for a variable? I.e.:

use std::os::raw::c_int;

mod c {
    #[link(name="...")]
    extern "C" {
        pub static VAR: c_int;
    }
}

pub static VAR: c_int = unsafe { c::VAR };

This results in a compiler error: "cannot read from extern static". What is the correct way (if there is one) to do this?

2
  • 2
    the correct way is to use unsafe Commented Apr 24, 2021 at 16:45
  • 3
    You can still offer some safe interface around that variable through some getter/setter. Within that interface it'll be unsafe, just like the add example. Commented Apr 24, 2021 at 16:47

1 Answer 1

2

It should be unsafe when it is indeed unsafe, although you can make a static borrow of the imported global variable.

static VAR: &i32 = unsafe { &c::VAR };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.