Unsafe Ffi
64 articles
Best Practices for Unsafe Code in Rust
Minimize unsafe blocks, isolate them in dedicated modules, and document the specific safety invariants they uphold to maintain Rust's memory guarantees.
Common Unsafe Patterns in Rust and When They're Justified
Unsafe Rust is justified for low-level operations like raw pointers and FFI when you manually verify safety invariants the compiler cannot check.
How to Access Mutable Statics in Rust
Access mutable statics in Rust by declaring them with `static mut` and wrapping all reads or writes in an `unsafe` block.
How to Audit Unsafe Code in Rust Dependencies (cargo-audit, cargo-geiger)
Install and run cargo-audit and cargo-geiger to scan Rust dependencies for security vulnerabilities and unsafe code.
How to Build a Shared Library (.so/.dll/.dylib) in Rust
Build a Rust shared library by setting crate-type to cdylib in Cargo.toml and running cargo build --release.
How to Build a Shared Rust Library for Android and iOS
Use the neon CLI tool to create and build a shared Rust library for Android and iOS with a single command.
How to Call C Functions from Rust
Call C functions in Rust by declaring them with extern "C" and invoking them inside an unsafe block.
How to call C functions from Rust FFI
Call C functions from Rust by declaring them with `extern "C"` and invoking them inside an `unsafe` block.
How to Call Python from Rust for Data Science (PyO3)
Use the PyO3 crate to initialize the Python interpreter and execute Python code directly within a Rust application.
How to Call PyTorch from Rust via FFI
You cannot call PyTorch directly from Rust via FFI because PyTorch is a C++ library with no stable C API; you must use a Rust binding crate like `pyo3` to call Python PyTorch or `torch-sys` to call the C++ core. Use `pyo3` to run Python code from Rust, which is the standard approach for accessing Py
How to call Rust from C
How to Call Rust from JavaScript/Node.js (Neon, napi-rs)
Use the napi-rs crate to define exported functions with #[napi] attributes, build them with 'napi build', and import the resulting binary in Node.js.
How to Call Rust from Python (PyO3, rust-cpython)
Use PyO3 with Maturin to compile Rust functions into a Python-importable shared library for high-performance integration.
How to Call Rust from Ruby, Java, or C#
You cannot call Rust directly from Ruby, Java, or C# because they run on different runtimes; instead, you must compile Rust into a shared library (`.so`, `.dll`, or `.dylib`) using the `#[no_mangle]` and `extern "C"` attributes, then load that library via each language's Foreign Function Interface (
How to Call Rust Functions from C
Call Rust functions from C by using #[no_mangle] and pub extern "C" attributes, then compile as a static library and link with gcc.
How to Call Unsafe Functions in Rust
You call unsafe functions in Rust by wrapping the function call inside an `unsafe` block, which explicitly tells the compiler you have manually verified that the operation is safe to perform.
How to create bindings with bindgen
Generate Rust bindings from C headers by running bindgen with the header path and output file arguments.
How to Debug FFI Issues in Rust
Fix Rust FFI errors by matching extern signatures, verifying symbol names, and wrapping calls in unsafe blocks.
How to Dereference Raw Pointers Safely
Dereference raw pointers in Rust by wrapping the access in an unsafe block to manually verify memory safety.
How to Document Unsafe Code in Rust
Document unsafe Rust code by adding a SAFETY comment explaining the specific invariants that make the operation safe.
How to Handle Callbacks Across FFI in Rust
Define an extern function pointer type, implement the callback with unsafe extern C, and pass it to foreign code.
How to Handle Errors Across the FFI Boundary
Prevent FFI panics from crashing your Rust program by wrapping calls in catch_unwind and returning Result types.
How to Implement Unsafe Traits (Send, Sync)
You cannot manually implement `Send` or `Sync` for types containing interior mutability or unsafe code without using `unsafe` blocks, as these are marker traits that the compiler enforces automatically. To opt-in a custom type to these traits, you must declare an `unsafe impl` block asserting that y
How to Link to C Libraries in Rust with build.rs
Link C libraries in Rust by printing linker flags in a build.rs script to specify the library name and search path.
How to Manage Memory Across FFI Boundaries
Use Box and raw pointers to explicitly transfer memory ownership between Rust and foreign languages.
How to Pass Structs Between Rust and C
How to Share Rust Code Between Mobile Platforms
Share Rust code between mobile platforms by creating a library crate, adding Android and iOS targets, and compiling for each specific architecture.
How to Transmute Types in Rust (and Why You Usually Shouldn't)
Direct type transmutation in Rust requires unsafe code and should be avoided in favor of safe casting or trait-based conversions.
How to Use bindgen to Generate Rust FFI Bindings
Use bindgen to automatically generate safe Rust FFI bindings from C header files with a single command.
How to Use cbindgen to Generate C Headers from Rust
Use `cbindgen` to automatically generate C-compatible header files from your Rust code by configuring a `cbindgen.toml` file and running the tool with your crate path.
How to Use cc and cmake Crates for Building C Code
Use the cc crate for simple C compilation and the cmake crate for complex C/C++ builds within Rust projects.
How to Use CString and CStr for FFI in Rust
Use CString to send Rust strings to C and CStr to read C strings back into Rust safely.
How to Use CString and CStr for FFI String Handling
Use CString::new to convert Rust strings to C-compatible null-terminated strings and CStr::from_ptr to safely read C strings back into Rust.
How to Use extern "C" Functions in Unsafe Rust
Call C functions in Rust by declaring them in an extern "C" block and invoking them within an unsafe block.
How to use extern crate for FFI
Use `extern` blocks and `#[link]` attributes to call foreign functions in Rust, not `extern crate`.
How to Use Inline Assembly in Rust
You use inline assembly in Rust via the `asm!` macro (available in nightly Rust) or the `std::arch::asm` module, which allows you to embed assembly instructions directly into your code while maintaining type safety and memory safety guarantees.
How to use libc crate
The `libc` crate provides Rust bindings to standard C library functions, allowing you to call low-level system APIs like `fork`, `open`, or `getpid` directly from safe Rust code.
How to Use Miri to Detect Undefined Behavior in Rust
Run cargo miri run or cargo miri test to detect undefined behavior in Rust code using dynamic analysis.
How to Use Opaque Pointers for FFI in Rust
Use *mut c_void in Rust FFI to safely pass opaque pointers to C, casting them back to concrete types only within unsafe blocks.
How to use raw pointers
Declare raw pointers as *const T or *mut T and dereference them inside an unsafe block to access memory directly.
How to Use Raw Pointers in Rust
Use raw pointers in Rust by declaring `*const T` or `*mut T` and accessing them inside an `unsafe` block to bypass safety checks.
How to Use Rust in Android Applications (via JNI/NDK)
Build Rust code for Android using cargo-ndk to generate native libraries for JNI integration.
How to Use Rust in iOS Applications
You cannot directly link Rust binaries into iOS applications because Apple's toolchain requires static libraries compiled with specific flags and architecture support that standard Rust tooling doesn't provide out of the box.
How to Use Rust with Flutter via FFI
You can integrate Rust into a Flutter app by compiling Rust code into a dynamic library (`.so`, `.dylib`, or `.dll`) and calling it from Flutter's platform channels using the C FFI.
How to Use Rust with Godot (gdext)
You use Rust with Godot by leveraging the `gdext` crate (formerly `godot-rust`), which generates safe, idiomatic Rust bindings for the Godot engine via the GDExtension API.
How to Use Rust with React Native via FFI
You must compile Rust code into a C++ library to use it with React Native, as direct FFI is not supported by the JavaScript engine.
How to Use std::ptr for Pointer Operations
Use std::ptr functions inside unsafe blocks to perform low-level memory reads, writes, and copies in Rust.
How to Use the cxx Crate for Rust/C++ Interop
The `cxx` crate is not used for building the Rust compiler itself; it is a library for safe Rust/C++ interoperability in application code. To use `cxx` in your project, add the dependency to your `Cargo.toml` and define your C++ bindings in a `#[cxx::bridge]` module.
How to Use the libc Crate in Rust
Add libc to Cargo.toml and import functions with use statements to call C library APIs from Rust.
How to use transmute safely
Use std::mem::transmute inside an unsafe block only when you guarantee identical memory layouts between types.
How to Use UniFFI for Cross-Platform Mobile Bindings
UniFFI generates safe, idiomatic bindings for your Rust code to be called from mobile languages like Swift and Kotlin. Add the `uniffi` crate to your `Cargo.toml`, define your API in a `.udl` file, and run the build script to generate the bindings.
How to Use Union Types in Rust
Define a union with the `union` keyword and access its fields inside an `unsafe` block to manage overlapping memory safely.
How to Wrap a C Library in a Safe Rust API
Use the bindgen crate to generate Rust bindings for C headers and wrap them in safe functions for error handling.
How to Wrap Unsafe Code in a Safe API
Wrap unsafe code in a safe API by isolating the unsafe block within a public function that guarantees safety invariants to callers.
How to Write Safe Abstractions Over Unsafe Code
Wrap unsafe operations in a safe function that validates inputs and isolates the `unsafe` block to prevent memory safety issues from leaking into your application.
How to write safe wrappers around unsafe code
Wrap unsafe Rust code in a safe function that validates inputs to prevent undefined behavior.
What Are the Rules for Unsafe Code Soundness?
Unsafe code soundness requires manual adherence to memory safety rules within `unsafe` blocks to prevent undefined behavior.
What are the safety invariants of unsafe
Unsafe Rust requires the programmer to manually guarantee memory safety, valid pointers, and single-threaded access to mutable statics since the compiler skips these checks.
What Can You Do Inside an unsafe Block?
An unsafe block in Rust allows you to perform operations like dereferencing raw pointers or calling unsafe functions by manually guaranteeing their safety.
What Is the Difference Between staticlib and cdylib in Rust?
staticlib creates a static archive for direct linking, while cdylib creates a dynamic shared library with a C-compatible ABI for external use.
What Is the Unsafe Contract and How to Document It
Unsafe Rust allows bypassing memory safety checks for low-level tasks, documented by wrapping code in unsafe blocks with safety justifications.
What Is Undefined Behavior in Rust?
Undefined behavior in Rust is unpredictable program execution caused by violating memory safety rules, often occurring in unsafe code blocks.
What is unsafe in Rust and when to use it
Unsafe Rust allows bypassing compiler safety checks for low-level tasks like raw pointer access and FFI, requiring manual memory safety verification.
What Is Unsafe Rust and When Should You Use It?
Unsafe Rust bypasses safety checks for low-level operations and should only be used when safe Rust is insufficient.