Skip to main content

r_ffi_checked

Attribute Macro r_ffi_checked 

Source
#[r_ffi_checked]
Expand description

Generate main-thread-checked wrappers for R FFI functions.

Apply this to an extern "C-unwind" block to generate, for each non-variadic function, a pair of entry points:

  • The original name (e.g. Rf_allocVector) — a wrapper that runs the call through miniextendr_api::with_r_thread: directly on R’s main thread, and a panic on any other thread.
  • A *_unchecked sibling (Rf_allocVector_unchecked) — the raw extern "C-unwind" declaration with no main-thread assertion.

User code should reach for the checked variant by default; the unchecked sibling exists for three known-safe contexts:

  1. Inside ALTREP callbacks — R is already calling us on the main thread, so the assertion would always pass.
  2. Inside a with_r_unwind_protect body — the guard runs on R’s main thread, so the assertion is redundant.
  3. Inside a with_r_thread body — the assertion is redundant; you are already where you needed to be.

The build-time lint MXL301 enforces this: calling *_unchecked outside one of those three contexts is a compile-time error.

§Tradeoffs at a glance

VariantAsserts main threadWhen to use
Rf_foo (checked)yesdefault
Rf_foo_uncheckednoALTREP callbacks, with_r_unwind_protect, with_r_thread

§Behavior

Every non-variadic function calls its *_unchecked sibling inside with_r_thread, which panics off R’s main thread before the call reaches R. This applies to value-returning functions (SEXP, i32, etc.), pointer-returning functions (*const T, *mut T), and never-returning ones (Rf_error).

§Initialization Requirement

miniextendr_runtime_init() must be called before using any wrapped function. Calling before initialization will panic with a descriptive error message.

§Limitations

  • Variadic functions are passed through unchanged (no wrapper)
  • Statics are passed through unchanged
  • Functions with #[link_name] are passed through unchanged

§Example

ⓘ
#[r_ffi_checked]
unsafe extern "C-unwind" {
    // Panics off R's main thread
    pub fn Rf_ScalarInteger(arg1: i32) -> SEXP;
    pub fn INTEGER(x: SEXP) -> *mut i32;
}