AI Languages Updated Nov 21, 2026 Ubuntu 24.04 LTS (Rust 1.82, GCC 13, Clang 18)

Safe Rust FFI: Calling C/C++ Shared Libraries on Linux

Practical Linux guide to calling native C/C++ shared libraries from Rust safely using extern "C", build.rs linking, bindgen bindings, and RAII wrappers that encapsulate unsafe code.
Z
Zaisha
Staff Writer · Verified Editor
Published Oct 5, 2026 · Updated Nov 21, 2026 · 4 min read · 627 words
Quick Overview

This deep-dive covers rust ffi c shared library linux with actionable analysis, practical implications, and expert insights.

Safe Rust FFI: Calling C/C++ Shared Libraries on Linux

Why Wrapping C Libraries Safely in Rust Requires Strict Boundaries

Linux systems rely on decades of battle-tested C and C++ shared libraries (libzstd, libsqlite3, libssl, hardware SDKs). Rust's Foreign Function Interface (FFI) calls native C functions with zero runtime overhead, but the moment you step inside unsafe, the Rust compiler cannot verify null pointers, buffer lengths, or C memory ownership. The proven pattern is isolating raw bindings in a private ffi module and exposing a safe, idiomatic Rust API backed by Result and Drop.

Step 1: Create a Sample C Library on Ubuntu

Install GCC and Clang, then build a small C library (csrc/hashlib.c) that allocates an opaque context handle and hashes a C string:

// csrc/hashlib.h
#ifndef HASHLIB_H
#define HASHLIB_H
#include <stddef.h>
#include <stdint.h>

typedef struct HashCtx HashCtx;

HashCtx* hash_ctx_new(uint64_t seed);
uint64_t hash_ctx_compute(const HashCtx* ctx, const char* input);
void hash_ctx_free(HashCtx* ctx);
#endif
// csrc/hashlib.c
#include "hashlib.h"
#include <stdlib.h>

struct HashCtx {
    uint64_t seed;
};

HashCtx* hash_ctx_new(uint64_t seed) {
    HashCtx* ctx = (HashCtx*)malloc(sizeof(HashCtx));
    if (!ctx) return NULL;
    ctx->seed = seed;
    return ctx;
}

uint64_t hash_ctx_compute(const HashCtx* ctx, const char* input) {
    if (!ctx || !input) return 0;
    uint64_t h = ctx->seed;
    while (*input) {
        h = (h * 131) ^ (unsigned char)(*input++);
    }
    return h;
}

void hash_ctx_free(HashCtx* ctx) {
    free(ctx);
}

Step 2: Compile and Link Automatically in build.rs

Add cc = "1" under [build-dependencies] in Cargo.toml and compile the C code automatically during cargo build:

// build.rs
fn main() {
    println!("cargo:rerun-if-changed=csrc/hashlib.c");
    println!("cargo:rerun-if-changed=csrc/hashlib.h");

    cc::Build::new()
        .file("csrc/hashlib.c")
        .include("csrc")
        .warnings(true)
        .compile("hashlib");
}

For an already-installed system shared library (like libzstd.so), emit println!("cargo:rustc-link-lib=zstd"); instead of compiling with cc.

Step 3: Isolate unsafe Behind a Safe RAII Wrapper

In src/lib.rs, wrap the opaque NonNull<HashCtx> pointer so callers never touch raw pointers, cannot forget to free memory, and receive clean Rust errors on invalid UTF-8/null bytes:

use std::ffi::{c_char, CString, NulError};
use std::ptr::NonNull;

mod ffi {
    use std::ffi::c_char;

    #[repr(C)]
    pub struct HashCtx {
        _private: [u8; 0],
    }

    extern "C" {
        pub fn hash_ctx_new(seed: u64) -> *mut HashCtx;
        pub fn hash_ctx_compute(ctx: *const HashCtx, input: *const c_char) -> u64;
        pub fn hash_ctx_free(ctx: *mut HashCtx);
    }
}

pub struct Hasher {
    raw: NonNull<ffi::HashCtx>,
}

impl Hasher {
    pub fn new(seed: u64) -> Result<Self, &'static str> {
        // SAFETY: hash_ctx_new returns either a valid heap pointer or null on OOM.
        let ptr = unsafe { ffi::hash_ctx_new(seed) };
        let raw = NonNull::new(ptr).ok_or("failed to allocate C HashCtx")?;
        Ok(Self { raw })
    }

    pub fn compute(&self, input: &str) -> Result<u64, NulError> {
        let c_str = CString::new(input)?;
        // SAFETY: self.raw is guaranteed non-null and alive for &self; c_str is null-terminated.
        Ok(unsafe { ffi::hash_ctx_compute(self.raw.as_ptr(), c_str.as_ptr()) })
    }
}

impl Drop for Hasher {
    fn drop(&mut self) {
        // SAFETY: self.raw was allocated by hash_ctx_new and is freed exactly once here.
        unsafe {
            ffi::hash_ctx_free(self.raw.as_ptr());
        }
    }
}

Step 4: Verify Zero Leaks with Cargo Test and Valgrind

sudo apt install -y valgrind
cargo test
valgrind --leak-check=full --error-exitcode=1 ./target/debug/deps/rust_ffi_demo-*

Summary

By pairing build.rs (or bindgen) with NonNull<T>, CString, and Drop, you can tap into Linux's vast ecosystem of native C and C++ shared libraries while keeping 99 percent of your Rust codebase completely safe and memory-leak free.

Tested & Verified Environment
Author Verified
Operating System: Ubuntu 24.04 LTS (Rust 1.82, GCC 13, Clang 18)
Verification Date: Nov 21, 2026
Testing Methodology & Notes: Built and linked a C shared library (.so) via build.rs on Ubuntu 24.04, wrapped opaque C pointers in a Rust struct implementing Drop, and verified zero leaks under Valgrind.

Was this technical analysis helpful?

Your feedback informs our benchmark updates and ongoing article audits.

✓ Thank you for your feedback! Our editorial engineers review submissions weekly.

Frequently Asked Questions

Structured for search engines and AI answer systems (AEO/GEO).

Write extern "C" manually only for 1 to 5 simple functions. For any real C library with structs, enums, or platform-dependent typedefs, use bindgen in build.rs so struct layouts never drift out of sync with C headers.

Either expose a thin extern "C" shim around your C++ classes, or use the cxx crate (cxx.rs) which generates type-safe, zero-overhead C++/Rust bridges directly.

On Linux, cargo:rustc-link-search tells the build-time linker where to find libfoo.so, not the runtime dynamic loader (ld.so). Install the library into /usr/local/lib and run sudo ldconfig, or pass -Wl,-rpath,$ORIGIN during linking.

Run your Rust test binary under Valgrind (valgrind --leak-check=full ./target/debug/my_ffi_test) or AddressSanitizer to verify every C allocation is matched by its Drop free call.

More answers in our FAQ hub.

Z
Zaisha

Tech journalist covering AI, software, and emerging technology with a focus on practical insights.

Testing Standards: Tutorials and guides are hands-on tested on Ubuntu Linux workstations before release.
View all articles by Zaisha

Practical Linux &amp; Applied AI Newsletter

Get new tested tutorials and benchmark comparisons delivered directly to your inbox. Zero spam.

Join Weekly guides readers getting our weekly digest.

  • Practical Linux administration & terminal workflows
  • Tested open-source AI setups & benchmarks
  • Zero spam - unsubscribe anytime

Join Weekly guides readers · Weekly digest · Unsubscribe anytime. RSS

Continue Exploring