Categories
Tags
3d ABI Actions algorithms alignment analyze APIT Arc Architecture arm array ascii ash assembly asynchronous attribute base64 bithacks Blogging box c c23 cdylib CHAR_BIT clamp clang clang-format client clippy cmake compiler Computer concat concurrency const_fn constexpr contravariant cos covariant cpp cpu crate CS Customization cybersecurity DataStructure db debugging Demo deserialization discrete dll doc DP drawio dtruss dylib Dynamic emulator example Example FFI ffmpeg flamegraph flat_map fold format FP fsanitize Functional FunctionalProgramming functions futures Fuwari game GATs gcc gccrs generics gitignore glibc GUI hacking hashmap haskell heap hyperfine Imperative inference intel interop invariant iterator join justfile kernel LaTeX leak LFU limits linux lto MachineLearning macOS map Markdown math ML mmap mod mp3 nc nextest OnceLock optimization OS ownership panic parallels perf physics pin postgresql procedure product profiling pub radare2 rayon release reverse RPIT rust sanitizer Science science serialization server shift SIMD sin size SmallProjects so socket std strace String StringView strip strlen struct sum super surrealdb SWAR swisstable synchronous syscall tan test thread time toml tracing traits trap triangulation type uint32_t UnsafeRust utf16 utf8 vector Video vulkan wsl x86_64 xilem zig
196 words
1 minutes
no_mangle
- The
#[no_mangle]attribute in Rust tells the compiler not to change (mangle) the name of a function or variable in the compiled binary.
What is Name Mangling?
- Normally, the Rust compiler transforms your original function names into an encoded string (e.g., adding module paths, crate names, and type signatures) so the linker can uniquely identify them.
Why Use #[no_mangle]?
- • Foreign Function Interface (FFI): It allows other languages like C, C++, or Python to call your Rust code by looking up the exact, plain function name you wrote instead of a scrambled compiler symbol.
- • WebAssembly (WASM): It keeps exported Rust functions visible and accessible when compiled to WASM.
- • Entry Points / Plugins: It preserves the raw symbol name for dynamic linking or loading shared libraries.
Important Notes
- • Safety & Unsafe Attributes: Because disabling name mangling can lead to symbol name collisions and undefined behavior if two different libraries use the same name, modern Rust (Edition 2024 / Rust 1.82+) requires writing it as #[unsafe(no_mangle)] to acknowledge these safety risks.
- • Usage Example:
#[unsafe(no_mangle)]
pub extern "C" fn hello_from_rust() {
println!("Hello from Rust!");
}- Are you trying to call Rust from C/C++, export a function to WebAssembly, or fix a compiler warning about unsafe attributes?