|
| 1 | +Raw FFI bindings to platform-specific system libraries. |
| 2 | + |
| 3 | +- Crate [`::libc`]. |
| 4 | +- [docs.rs](https://docs.rs/libc) |
| 5 | +- [crates.io](https://crates.io/crates/libc) |
| 6 | +- [GitHub](https://github.com/rust-lang/libc) |
| 7 | + |
| 8 | +--- |
| 9 | + |
| 10 | +`libc` provides raw bindings to the C standard library |
| 11 | +and platform-specific system APIs. |
| 12 | +It is the foundational crate for most Rust FFI that |
| 13 | +needs to interoperate with system and native libraries. |
| 14 | + |
| 15 | +The crate exports types, constants, and function signatures |
| 16 | +matching the platform's C headers. |
| 17 | +On Linux this includes POSIX APIs and Linux-specific extensions; |
| 18 | +on macOS, the Darwin system APIs; on Windows, a small subset of CRT functions. |
| 19 | + |
| 20 | +Common uses include: |
| 21 | +- Calling POSIX functions like [`open`], [`read`], [`write`], [`mmap`] |
| 22 | +- Accessing system constants like [`EINVAL`], [`O_RDONLY`], [`SIGTERM`] |
| 23 | +- Defining types for FFI function signatures ([`c_int`], [`c_char`], [`size_t`]) |
| 24 | +- Low-level memory operations like [`malloc`] and [`free`] |
| 25 | + |
| 26 | +Note that basic C type aliases like `c_int` and `c_char` |
| 27 | +are available directly in [`std::ffi`]. |
| 28 | +The [`nix`](https://docs.rs/nix) |
| 29 | +and [`rustix`](https://docs.rs/rustix) |
| 30 | +crates provide additional high-level safe Unix API bindings. |
| 31 | +For Windows, the [`windows`](https://docs.rs/windows) |
| 32 | +and [`windows-sys`](https://docs.rs/windows-sys) crates |
| 33 | +provide bindings to the Win32 API. |
| 34 | + |
| 35 | +## Examples |
| 36 | + |
| 37 | +Querying system configuration not exposed by `std`: |
| 38 | + |
| 39 | +```rust |
| 40 | +let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; |
| 41 | +assert!(page_size > 0); |
| 42 | + |
| 43 | +let uid = unsafe { libc::getuid() }; |
| 44 | +let pid = unsafe { libc::getpid() }; |
| 45 | +assert!(pid > 0); |
| 46 | +``` |
| 47 | + |
| 48 | +[`open`]: crate::libc::open |
| 49 | +[`read`]: crate::libc::read |
| 50 | +[`write`]: crate::libc::write |
| 51 | +[`mmap`]: crate::libc::mmap |
| 52 | +[`EINVAL`]: crate::libc::EINVAL |
| 53 | +[`O_RDONLY`]: crate::libc::O_RDONLY |
| 54 | +[`SIGTERM`]: crate::libc::SIGTERM |
| 55 | +[`c_int`]: crate::libc::c_int |
| 56 | +[`c_char`]: crate::libc::c_char |
| 57 | +[`size_t`]: crate::libc::size_t |
| 58 | +[`malloc`]: crate::libc::malloc |
| 59 | +[`free`]: crate::libc::free |
| 60 | +[`std`]: crate::std |
0 commit comments