# Foreign Function Interface

Rust provides a Foreign Function Interface (FFI) to C libraries. Foreign functions must be declared inside an `extern` block annotated with a `#[link]` attribute containing the name of the foreign library.

``````use std::fmt;

// this extern block links to the libm library
extern {
// this is a foreign function
// that computes the square root of a single precision complex number
fn csqrtf(z: Complex) -> Complex;

fn ccosf(z: Complex) -> Complex;
}

// Since calling foreign functions is considered unsafe,
// it's common to write safe wrappers around them.
fn cos(z: Complex) -> Complex {
unsafe { ccosf(z) }
}

fn main() {
// z = -1 + 0i
let z = Complex { re: -1., im: 0. };

// calling a foreign function is an unsafe operation
let z_sqrt = unsafe { csqrtf(z) };

println!("the square root of {:?} is {:?}", z, z_sqrt);

// calling safe API wrapped around unsafe operation
println!("cos({:?}) = {:?}", z, cos(z));
}

// Minimal implementation of single precision complex numbers
#[repr(C)]
#[derive(Clone, Copy)]
struct Complex {
re: f32,
im: f32,
}

impl fmt::Debug for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.im < 0. {
write!(f, "{}-{}i", self.re, -self.im)
} else {
write!(f, "{}+{}i", self.re, self.im)
}
}
}
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.6742805,"math_prob":0.98480296,"size":1280,"snap":"2020-45-2020-50","text_gpt3_token_len":345,"char_repetition_ratio":0.12460815,"word_repetition_ratio":0.0,"special_character_ratio":0.33046874,"punctuation_ratio":0.2421875,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95550805,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-24T06:39:11Z\",\"WARC-Record-ID\":\"<urn:uuid:563dbe4f-86b7-45e1-a846-7f86d9a836c6>\",\"Content-Length\":\"39988\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:bc1d8656-a4d5-4021-b867-d4800fff0b5c>\",\"WARC-Concurrent-To\":\"<urn:uuid:b6eef8e6-3ad9-4ef7-9d1e-1a6aada04f65>\",\"WARC-IP-Address\":\"13.32.207.109\",\"WARC-Target-URI\":\"https://doc.rust-lang.org/nightly/rust-by-example/std_misc/ffi.html\",\"WARC-Payload-Digest\":\"sha1:O4UUE3II4XFYJ4N4X2KLY36JSNXAZGV6\",\"WARC-Block-Digest\":\"sha1:BMMLO25OOH5CX32G67WEUTYN2TZEFTAV\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107882102.31_warc_CC-MAIN-20201024051926-20201024081926-00099.warc.gz\"}"}