2022-12-21 16:36:30 +01:00
|
|
|
# Calling External Code
|
|
|
|
|
|
|
|
|
|
Functions from other languages might violate the guarantees of Rust. Calling
|
|
|
|
|
them is thus unsafe:
|
|
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
|
extern "C" {
|
|
|
|
|
fn abs(input: i32) -> i32;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
unsafe {
|
|
|
|
|
// Undefined behavior if abs misbehaves.
|
|
|
|
|
println!("Absolute value of -3 according to C: {}", abs(-3));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
2023-01-17 16:41:23 +00:00
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
|
|
|
|
|
This is usually only a problem for extern functions which do things with pointers which might
|
|
|
|
|
violate Rust's memory model, but in general any C function might have undefined behaviour under any
|
|
|
|
|
arbitrary circumstances.
|
|
|
|
|
|
2023-01-20 10:56:30 +00:00
|
|
|
The `"C"` in this example is the ABI;
|
|
|
|
|
[other ABIs are available too](https://doc.rust-lang.org/reference/items/external-blocks.html).
|
|
|
|
|
|
2023-01-17 16:41:23 +00:00
|
|
|
</details>
|