19.6 Unsafe Rust at the R Boundary

RUSTSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page Send and Sync

19.6.1 Motivation

The FFI to R’s C API requires unsafe code. Raw pointers must be dereferenced. Calling conventions must be correct, and the signatures must match what the package was compiled against. A mistake is undefined behavior.

Rust’s unsafe keyword allows code that the compiler cannot prove safe. But unsafe does not mean “uncontrolled”. It means “the programmer has checked what the compiler cannot”. The programmer must document invariants and verify them. r-in-rust keeps all of its unsafe code in the few crates that implement R’s C API.

19.6.2 The permissions unsafe grants

The Rust Book lists five things unsafe permits that the compiler normally forbids. The four that matter at the R boundary are below; the fifth is reading the fields of a union, and the Rust Reference adds a few rarer cases.

First: dereference raw pointers. A *const T or *mut T is a raw pointer. The compiler cannot prove it is valid. To dereference it, the code must be inside an unsafe block. The programmer is claiming: “I have checked that this pointer is valid”.

Second: call unsafe functions. Some functions are unsafe to call. A C function can have undefined behavior if called with certain arguments, so a function declared in an extern "C" block is unsafe to call unless the block marks it safe, as is any Rust function declared unsafe fn. Calling one requires an unsafe block.

Third: access or mutate mutable statics. A global mutable variable is not thread-safe by default, and a static declared in an extern block, such as R’s R_DimSymbol, belongs to C code that Rust cannot check. Reading or writing either requires unsafe.

Fourth: implement unsafe traits. Some traits are marked unsafe. Implementing them requires an unsafe impl block. The implementer claims that the implementation is correct.

All of them require explicit unsafe markers. The code stands out. An auditor can search for all unsafe blocks and review them carefully.

19.6.3 The need for unsafe at the R boundary

Crossing from Rust to C requires unsafe. The R C API uses raw pointers. A SEXP is a raw pointer to a SEXPREC structure. To call an R function from Rust, the code must:

  1. Create a raw pointer to R data.
  2. Call the C function with that pointer.
  3. Interpret the returned pointer.
  4. Manage memory according to R’s rules.

Here is a minimal example. It assumes extern "C" declarations that mirror Rinternals.h, the kind a bindings crate generates:

unsafe {
    let x = Rf_protect(Rf_allocVector(REALSXP, 10));
    let dim = Rf_protect(Rf_allocVector(INTSXP, 2));
    *INTEGER(dim).add(0) = 2;
    *INTEGER(dim).add(1) = 5;
    Rf_setAttrib(x, R_DimSymbol, dim);
    Rf_unprotect(2);
}

The unsafe block is necessary because:

  • Every function here is a C function declared in an extern "C" block, so each call is unsafe.
  • Rf_allocVector returns a raw pointer, and INTEGER returns another one that the code writes through.
  • Rf_protect and Rf_unprotect, the functions behind C’s PROTECT and UNPROTECT macros, change R’s protect stack, which the code must leave balanced.

Rust cannot verify any of these. The C API has no type signatures that express these invariants. The programmer must verify them by reading documentation. Any allocation can trigger a collection, so a freshly allocated value must be protected before it is handed to anything that can allocate again.

19.6.4 Documenting invariants

When unsafe code is used, the surrounding safe code must document what it relies on. These are the invariants that make the unsafe code correct.

/// Allocates a REALSXP of `size` elements and leaves it PROTECTed.
///
/// SAFETY: the R runtime must be initialized, and this must run on R's thread.
///
/// The caller owns one protect stack entry and must balance it with
/// `Rf_unprotect(1)` before returning to R. Protection is a stack, so the
/// caller unprotects in reverse order of protection.
unsafe fn allocate_vector(size: R_xlen_t) -> SEXP {
    Rf_protect(Rf_allocVector(REALSXP, size))
}

The invariants are not checked automatically. But they are written down. A future developer knows what to verify.

19.6.5 The burden of proof

Every unsafe block shifts verification from the compiler to the programmer. The programmer must prove:

  1. Raw pointers are valid.
  2. Functions are called with correct arguments.
  3. Return values are interpreted correctly.
  4. Memory is managed correctly.
  5. Thread safety rules are obeyed.

These proofs are informal. They live in code comments and documentation. If the proof is wrong, the program has undefined behavior.

For a runtime engineer, this burden is high. The R C API is complex. Its documentation is incomplete in places. Edge cases exist. Getting everything right is difficult.

19.6.6 Other systems

Most C extensions to dynamic languages cross the boundary with unsafe code or its equivalent. Python uses raw C pointers with no type safety. The C extension author must verify all invariants by hand.

Java uses the Java Native Interface (JNI). Crossing the boundary still requires careful verification of invariants. But the JNI provides more type information than the bare C API.

Go calls C through cgo, with rules, checked at run time, about which Go pointers C code may keep, and uses its unsafe package for raw pointer conversions. The burden is similar to Rust’s.

The pattern is universal: crossing to C requires giving up compile-time verification. The cost is that bugs become subtle and difficult to find. Memory corruption, undefined behavior, and data races lurk at the boundary.

The Rust approach is to make this explicit. An unsafe block stands out. An auditor can review all unsafe code in the codebase at once. The risk is localized.

19.6.7 r-in-rust’s approach

The rrs interpreter crates forbid unsafe_code at the lint level, checked by a gate. The C API crates exist to speak C and are the only ones permitted the keyword, and the gate names them explicitly and rejects it anywhere else. The unsafety is not absent, it is confined to the crates whose whole job is the boundary.

That split is the design, and it is what let the C API ship without weakening the interpreter:

  1. rrs is a standalone interpreter owning its heap, collector and symbol table, in crates that cannot write unsafe at all.
  2. The C API crates implement R’s exported entry points over that interpreter, and they carry every raw pointer in the system.
  3. A package’s compiled code links against those entry points exactly as it links against GNU R’s, because the headers present the same function-accessor surface.
  4. The boundary is therefore a small, named set of crates, not a property of the whole codebase.

An interpreter built in safe Rust is easier to reason about, because the boundary crates are the only place where memory assumptions must be checked by hand. Inside the interpreter crates, the code never calls native code directly; every call into a package’s compiled code goes through the C API crates.

Forbidding unsafe_code has real costs. Some optimizations become impossible. Direct memory manipulation is off-limits. Some patterns from C libraries cannot be ported directly. In return, the interpreter crates cannot cause a use-after-free, a buffer overflow or any other undefined behavior from invalid memory access, assuming the standard library and the few dependencies they use are sound. The guarantee stops at the boundary: a bug in the C API crates, or in a package’s own C code running in the same process, can still corrupt the interpreter’s memory.

A thin, auditable wrapper at the interpreter boundary can provide safe access to an rrs interpreter from R code. The bulk of rrs remains safe Rust.

Defining a safe wrapper around unsafe code imposes a mental cost. The wrapper designer must identify all ways the unsafe code can fail, document those ways clearly, prevent the caller from triggering any of them, and review the wrapper to verify the prevention. That cost is paid once per wrapper, and from then on the compiler checks every call through it. In rrs, the C API crates sit at that boundary: they translate between R’s C API and rrs types, all unsafe code lives in them, and the rest of rrs is safe Rust.

19.6.8 When unsafe becomes necessary

Interoperating with CRAN packages needed unsafe code, and it is now written. Native packages call R’s C functions, and something has to hold the raw pointers on the way through. A mistake there corrupts the rrs heap or breaks an assumption the package was compiled with.

At that point, the choice is:

  1. Write careful unsafe code that has been reviewed and tested.
  2. Accept a compatibility cost: some packages cannot run.
  3. Design around the problem: rewrite packages, provide substitute implementations.

r-in-rust took option 1, and confined the result to the C API crates. In the census of 2026-08-18, twenty-eight of the thirty most downloaded compiled packages installed and all twenty-eight loaded, and the two that failed were StanHeaders and rstan, which needs it; the ledger suspects a file-system flake behind the StanHeaders failure, not a fault at the boundary. Option 2 still applies where a package needs a base R function that rrs does not have yet.

What safety invariants must an rrs interpreter wrapper uphold to allow CRAN packages to use it safely?

19.6.9 Safe wrappers around unsafe code

Best practice is to minimize unsafe by wrapping it in safe abstractions. For lifetimes that do not nest strictly, the right mechanism is independent preservation outside the protect stack.

pub struct PreservedVector {
    ptr: SEXP,
}

impl PreservedVector {
    pub fn new(size: R_xlen_t) -> Self {
        unsafe {
            let ptr = Rf_protect(Rf_allocVector(REALSXP, size));
            R_PreserveObject(ptr);   // rooted independently of the stack
            Rf_unprotect(1);         // balanced before this call returns
            PreservedVector { ptr }
        }
    }

    pub fn get(&self, i: usize) -> f64 {
        unsafe {
            let len = Rf_xlength(self.ptr) as usize;
            assert!(i < len, "index {i} out of bounds for length {len}");
            *REAL(self.ptr).add(i)
        }
    }
}

impl Drop for PreservedVector {
    fn drop(&mut self) {
        unsafe { R_ReleaseObject(self.ptr); }
    }
}

R_PreserveObject and R_ReleaseObject keep a precious list, not a stack, so releases can happen in any order, which is what Rust’s drop order needs. “Writing R Extensions” warns that this is less efficient than the protect stack and should be used sparingly: by default the precious list is a linked list, and each release searches it. get checks the index against the vector’s length, because a safe function that reads past the end would let safe code cause undefined behavior. And because the struct holds a raw pointer, it is automatically neither Send nor Sync, so it cannot leave the thread that created it.

Ordering is not the only hazard. Most R API functions can raise an R error, and R raises it with longjmp, which jumps over every Rust frame between the call and R’s error handler. Whether it runs their destructors depends on the platform, and Rust code cannot rely on it. Rust’s RFC 2945 makes that undefined behavior for any frame with a pending destructor and leaves it unspecified even for frames without one. Rf_allocVector raises an error when memory runs out, and R_PreserveObject allocates, so new as written is sound only when it runs on R’s main thread and no such error occurs. Bindings that handle this run each R call inside R_UnwindProtect. R calls a cleanup function when the error arrives; from there the Rust side can unwind its own frames normally and then resume R’s jump with R_ContinueUnwind, the same pattern “Writing R Extensions” describes for C++.

Protection is a stack discipline. UNPROTECT pops a count from the top, never a specific object. Rust’s drop order is unrelated to R’s protect order, so a Drop implementation that calls UNPROTECT corrupts the stack when drops occur out of protection order. That happens whenever C code protects something in between, or a protected value is moved out of its scope, stored in a struct or collection, or dropped early.

This pattern appears throughout FFI bindings. Rust’s standard library, for instance, wraps the operating system’s file calls (open, read, close on Unix) in the safe methods of std::fs::File. The unsafe code calls C directly, and the safe wrapper upholds its invariants.

19.6.10 Failure modes

The most common mistake is to misunderstand what unsafe permits. unsafe does not make undefined behavior safe. It makes the programmer responsible for proving correctness. If the proof is wrong, the behavior is still undefined.

Another mistake is to write a large block of unsafe code and assume it is correct because the Rust compiler accepted it. Inside an unsafe block the compiler still type-checks and borrow-checks everything it can, but it does not verify the invariants that the unsafe operations rely on.

A third mistake is to forget that unsafe code can affect safe code. If an unsafe block corrupts memory, the corruption propagates to code that was never marked unsafe. The boundaries between safe and unsafe are not always clear.

For these reasons, minimize unsafe code, isolate it, document it, and review it carefully.

Further reading

Where this appears

  • r-in-rust (rrs) Forbids unsafe_code in the interpreter crates and confines unsafe to the crates that implement R’s C API.

Where to go next

Back to top