Skip to content

Commit e843487

Browse files
authored
Merge pull request #1008 from bmusin/patch-18
collapse two examples into one to simplify reading
2 parents 0a4e899 + a27eff5 commit e843487

File tree

1 file changed

+10
-43
lines changed

1 file changed

+10
-43
lines changed

src/std_misc/ffi.md

Lines changed: 10 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -13,59 +13,26 @@ extern {
1313
// this is a foreign function
1414
// that computes the square root of a single precision complex number
1515
fn csqrtf(z: Complex) -> Complex;
16-
}
17-
18-
fn main() {
19-
// z = -1 + 0i
20-
let z = Complex { re: -1., im: 0. };
2116
22-
// calling a foreign function is an unsafe operation
23-
let z_sqrt = unsafe {
24-
csqrtf(z)
25-
};
26-
27-
println!("the square root of {:?} is {:?}", z, z_sqrt);
28-
}
29-
30-
// Minimal implementation of single precision complex numbers
31-
#[repr(C)]
32-
#[derive(Clone, Copy)]
33-
struct Complex {
34-
re: f32,
35-
im: f32,
36-
}
37-
38-
impl fmt::Debug for Complex {
39-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40-
if self.im < 0. {
41-
write!(f, "{}-{}i", self.re, -self.im)
42-
} else {
43-
write!(f, "{}+{}i", self.re, self.im)
44-
}
45-
}
46-
}
47-
```
48-
49-
Since calling foreign functions is considered unsafe, it's common to write safe
50-
wrappers around them.
51-
52-
```rust,ignore
53-
use std::fmt;
54-
55-
#[link(name = "m")]
56-
extern {
5717
fn ccosf(z: Complex) -> Complex;
5818
}
5919
60-
// safe wrapper
20+
// Since calling foreign functions is considered unsafe,
21+
// it's common to write safe wrappers around them.
6122
fn cos(z: Complex) -> Complex {
6223
unsafe { ccosf(z) }
6324
}
6425
6526
fn main() {
66-
// z = 0 + 1i
67-
let z = Complex { re: 0., im: 1. };
27+
// z = -1 + 0i
28+
let z = Complex { re: -1., im: 0. };
29+
30+
// calling a foreign function is an unsafe operation
31+
let z_sqrt = unsafe { csqrtf(z) };
32+
33+
println!("the square root of {:?} is {:?}", z, z_sqrt);
6834
35+
// calling safe API wrapped around unsafe operation
6936
println!("cos({:?}) = {:?}", z, cos(z));
7037
}
7138

0 commit comments

Comments
 (0)