Skip to content

Rust FFI — Foreign Function Interface with C, Python, and Other Languages

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust FFI. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust FFI enables calling C libraries with extern "C", exporting Rust functions for Python via PyO3, and creating Node.js native addons with napi-rs.

What You'll Learn

  • C FFI basics
  • PyO3 for Python
  • napi-rs for Node.js
  • Memory safety

Why It Matters

FFI bridges Rust with other ecosystems. DodaZIP uses FFI to wrap system libraries.

Real-World Use

Python performance modules, Node.js native addons, C library wrappers.

// C FFI
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[no_mangle]
pub extern "C" fn greet(name: *const std::os::raw::c_char) -> *mut std::os::raw::c_char {
    let name = unsafe { std::ffi::CStr::from_ptr(name) }
        .to_str()
        .unwrap_or("World");
    let result = format!("Hello, {}!", name);
    std::ffi::CString::new(result)
        .unwrap()
        .into_raw()
}

// Python via PyO3
use pyo3::prelude::*;

#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> String {
    (a + b).to_string()
}

#[pymodule]
fn mylib(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    Ok(())
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro