Skip to main content

r_ffi_checked

Attribute Macro r_ffi_checked 

Source
#[r_ffi_checked]
Expand description

Generate thread-safe wrappers for R FFI functions.

Apply this to an extern "C-unwind" block to generate wrappers that ensure R API calls happen on R’s main thread.

§Behavior

All non-variadic functions are routed to the main thread via with_r_thread when called from a worker thread. The return value is wrapped in Sendable and sent back to the caller. This applies to both value-returning functions (SEXP, i32, etc.) and pointer-returning functions (*const T, *mut T).

Pointer-returning functions (like INTEGER, REAL) are safe to route because the underlying SEXP must be GC-protected by the caller, and R’s GC only runs during R API calls which are serialized through with_r_thread.

§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" {
    // Routed to main thread via with_r_thread when called from worker
    pub fn Rf_ScalarInteger(arg1: i32) -> SEXP;
    pub fn INTEGER(x: SEXP) -> *mut i32;
}