Reputation: 3163
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?
Upvotes: 1
Views: 888
Reputation: 4775
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 };
Upvotes: 2