7.2 How R Calls C, C++, and Fortran

ABI AND FFISTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page What Is an ABI?, SEXPs

7.2.1 Motivation

R is an interpreter. C is compiled machine code. When an R package contains C code, the two must meet at a boundary. R must call the C routine and pass it data. The C routine must return a result to R. Three things govern the crossing: the platform’s calling convention, which fixes how arguments travel; R’s protection protocol, which keeps objects alive; and routine registration, which lets R find a routine by name.

7.2.2 Mental model: the call stack

The interpreter is itself C code, a loop that reads R bytecode or the AST and executes it. When R code calls .Call("add", a, b), the interpreter evaluates the arguments, then its do_dotcall finds the routine’s address and calls it like any other C function, with the arguments as SEXPs. The routine’s frame goes on the same machine stack, on top of the interpreter’s own frames, and the interpreter resumes when the routine returns.

The C routine runs at the same privilege level as the R interpreter. It sees the same memory. It can allocate memory, call functions, and corrupt anything. R has no protection against a buggy C routine and depends on the C programmer following the rules.

7.2.3 Symbol registration and the linker

A native R package is a compiled binary. At load time, R calls dyn.load(). The dynamic linker reads the binary and searches for function symbols. A typical C function in an R package looks like this:

SEXP add(SEXP a, SEXP b) {
  return ScalarInteger(INTEGER(a)[0] + INTEGER(b)[0]);
}

Without registration, R finds the routine by name when it is called: .Call("add", a, b) makes R search the loaded libraries for an exported symbol spelled add. Modern packages use symbol registration instead. The package provides a table of functions and their R-visible names:

static const R_CallMethodDef callMethods[] = {
  {"add", (DL_FUNC) &add, 2},
  {NULL, NULL, 0}
};

void R_init_mypackage(DllInfo *dll) {
  R_registerRoutines(dll, NULL, callMethods, NULL, NULL);
  R_useDynamicSymbols(dll, FALSE);
}

The call to R_useDynamicSymbols(dll, FALSE) turns off the fallback search, so R will not look up any name in this library that was not registered.

When the package loads, R calls R_init_mypackage(). The routine registers each C function with an R-visible name and an arity, and the address in the table is the one the package’s own code took with &add. A call by name now searches this table instead of the library’s symbols. A package whose NAMESPACE says useDynLib(mypackage, .registration = TRUE, .fixes = "C_") goes one step further: R creates an object for each registered routine, and .Call(C_add, a, b) hands R the address with no lookup at all.

A package that registers its routines does it in R_init_<pkg>(), which dyn.load() calls automatically when it loads the library. .Call with a string searches the registered table first and falls back to the library’s exported symbols unless R_useDynamicSymbols(dll, FALSE) was called. .Call with a registered routine object skips the search.

7.2.4 Calling conventions and argument passing

When R calls a C routine, arguments must pass in a specific way. On x86-64 Linux (System V ABI), the first six integer arguments go in registers: rdi, rsi, rdx, rcx, r8, r9. The return value comes back in rax. The C function add(SEXP a, SEXP b) receives its arguments in rdi and rsi.

All R objects reach C as SEXP values. When R calls add(a, b) it places the pointer to a in rdi and the pointer to b in rsi. What the C code can do with those pointers is narrower than it looks: Rinternals.h declares typedef struct SEXPREC *SEXP; and never defines the struct, so the package cannot dereference one. It calls INTEGER(a) instead, and that is a function call.

That is where ABI stability lives: in the exported surface, not in field offsets, which a conforming package never knew. The surface is the symbol names the linker resolves, the signatures and calling conventions those symbols promise, and the public constants and types the compiler baked into the binary. Change SEXPTYPE from unsigned int to something wider and every compiled package passes the wrong argument width. Move a field inside SEXPREC and a conforming package does not notice. The ones that notice are the ones that opted out, by defining USE_RINTERNALS before R 4.2.0 or by copying R’s internal headers.

7.2.5 PROTECT and the garbage collector agreement

R has a garbage collector. When C code holds a pointer to an R object, the object must not be freed while the C code is still using it. R uses an explicit protection mechanism: the protect stack.

C code must protect what it allocates, for as long as it uses it, because any allocation can trigger a collection. The garbage collector makes no assumptions about recent allocations. Nothing you allocate is protected implicitly. R keeps alive what you protect, what a protected object points to, and the arguments it passed in, and nothing else you create.

The protect-unprotect pattern is mandatory:

SEXP result = PROTECT(allocVector(REALSXP, 10));
// Use result...
UNPROTECT(1);  // Remove 1 item from protect stack
return result;

Each PROTECT() pushes onto the stack. Each UNPROTECT(n) pops n items. The order is a stack: last in, first out.

UNPROTECT takes a count, not an object after three PROTECTs c b a UNPROTECT pops the top UNPROTECT(1) pops c gone b a correct: c was on top what a destructor wants c b a release b UNPROTECT cannot do this

UNPROTECT releases in reverse order of protection, so it cannot release an object in the middle on its own. A destructor runs when its value dies, not when its slot reaches the top, which is why RAII over UNPROTECT is unsound.

The protect stack is process-global in GNU R. Every C routine on the call stack must balance its own PROTECT and UNPROTECT calls before it returns, and R warns about a “stack imbalance in ‘.Call’” when a routine does not. If a C function allocates 10 objects and forgets to PROTECT 3 of them, those objects are vulnerable to garbage collection. This happens even while the function is still using them.

7.2.6 Forgetting PROTECT

Consider this buggy C function:

SEXP bad_example(void) {
  SEXP x = Rf_allocVector(REALSXP, 1000000);   /* unprotected */
  SEXP y = Rf_allocVector(REALSXP, 1000000);   /* this allocation can collect x */
  REAL(x)[0] = 1.0;                            /* x may already be freed */
  return y;
}

The garbage collector does not know that x is still in use. It frees the memory. The C code then dereferences the freed pointer. Corruption or a crash follows.

Here is the corrected version:

SEXP good_example(void) {
  SEXP x = PROTECT(Rf_allocVector(REALSXP, 1000000));
  SEXP y = Rf_allocVector(REALSXP, 1000000);
  REAL(x)[0] = 1.0;
  UNPROTECT(1);
  return y;
}

A package with a PROTECT bug can pass its tests for years, because a collection has to land on exactly the allocation that leaves the object unprotected. R collects when its own heap counters pass a threshold, not when the machine runs low on memory, so the bug appears when the data size or the allocation pattern changes. gctorture(TRUE) makes R collect at every allocation, which is how such bugs are usually found.

7.2.7 Object lifetimes across the boundary

When R calls a C function and the function returns, the responsibility for protecting objects changes hands. An object that was protected on the protect stack while C code was running becomes unprotected when the C code returns.

Returning a SEXP confers no protection. The usual pattern is safe only because nothing allocates between the UNPROTECT and the return. Insert a single allocation after the UNPROTECT and the function breaks.

SEXP make_result(R_xlen_t n) {
  SEXP result = PROTECT(Rf_allocVector(REALSXP, n));
  /* fill result */
  UNPROTECT(1);
  return result;   /* safe only because nothing allocates after the UNPROTECT */
}

7.2.8 Handling errors and unwinding

R’s error mechanism uses longjmp(), a C feature that restores the stack to a saved point. The saved point was recorded earlier, with setjmp(), when R entered the context that will catch the error: a tryCatch(), or the top level. When code calls error(), R finds that context and longjmps to it.

If a C function calls an R function and that function errors, the jump skips the rest of the C function’s code, its UNPROTECT() calls included. The protect stack itself survives this. Each context records the height of the protect stack when it starts, and R restores that height before the jump lands, so protected objects do not leak. What does leak is everything R does not manage: memory from malloc(), an open file, a C++ object whose destructor never runs.

A C function that holds such resources while it calls back into R can use R_UnwindProtect(), which runs a cleanup function before the jump continues, or R_tryCatchError() and R_tryCatch(), which catch the condition in C.

Thread-safe R implementations must have per-thread protect stacks. A global protect stack makes it impossible to isolate errors or protect state across threads.

7.2.9 The cost of the agreement

The PROTECT/UNPROTECT protocol is explicit and manual. The programmer must reason about every allocation and every function call. This is tedious and error-prone.

Other C APIs ask for similar bookkeeping. CPython’s asks extension code to call Py_INCREF and Py_DECREF by hand for every reference it owns. Changing R’s protocol now would break every compiled package written against the current one.

This is why many R packages use Rcpp or other wrapping libraries. These libraries manage protection for the programmer: the C++ code does not call PROTECT(), and the wrapper keeps its objects alive itself.

But at the boundary where Rcpp meets the C API, the rules still apply. Rcpp just makes them easier to follow.

Further reading

  • Writing R Extensions <https://cran.r-project.org/doc/manuals/r-release/R-exts.html>, chapter 5 (System and foreign language interfaces).
  • Writing R Extensions <https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Garbage-Collection>, section 5.9.1 (Handling the effects of garbage collection), on PROTECT and UNPROTECT.
  • R Internals <https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Contexts>, section 1.4 (Contexts), on the contexts that longjmp() returns to.
  • System V AMD64 ABI <https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI>, formal specification of calling conventions.

Where this appears

  • threaded-r Symbol registration and PROTECT/UNPROTECT are threading hazards when the stack is not per-thread.
  • r-in-rust (rrs) The compatibility layer must implement PROTECT/UNPROTECT semantics exactly or C code will corrupt the Rust heap.

Where to go next

Back to top