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.

  1. use std::fmt;
  2. // this extern block links to the libm library
  3. #[link(name = "m")]
  4. extern {
  5. // this is a foreign function
  6. // that computes the square root of a single precision complex number
  7. fn csqrtf(z: Complex) -> Complex;
  8. fn ccosf(z: Complex) -> Complex;
  9. }
  10. // Since calling foreign functions is considered unsafe,
  11. // it's common to write safe wrappers around them.
  12. fn cos(z: Complex) -> Complex {
  13. unsafe { ccosf(z) }
  14. }
  15. fn main() {
  16. // z = -1 + 0i
  17. let z = Complex { re: -1., im: 0. };
  18. // calling a foreign function is an unsafe operation
  19. let z_sqrt = unsafe { csqrtf(z) };
  20. println!("the square root of {:?} is {:?}", z, z_sqrt);
  21. // calling safe API wrapped around unsafe operation
  22. println!("cos({:?}) = {:?}", z, cos(z));
  23. }
  24. // Minimal implementation of single precision complex numbers
  25. #[repr(C)]
  26. #[derive(Clone, Copy)]
  27. struct Complex {
  28. re: f32,
  29. im: f32,
  30. }
  31. impl fmt::Debug for Complex {
  32. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  33. if self.im < 0. {
  34. write!(f, "{}-{}i", self.re, -self.im)
  35. } else {
  36. write!(f, "{}+{}i", self.re, self.im)
  37. }
  38. }
  39. }