zuffi is a foreign function interface that lets R call functions in a shared library from their C declarations, with no wrapper code to write or compile.
- Calls go through a copy of libffi built into the package, on x86-64 and arm64 Linux and macOS and on x86-64 Windows; it needs no system library.
- A function is declared by pasting its C declaration, or by reading the library’s header with
ffi_include(), which runs the C preprocessor R was built with. - Conversions are checked: a value the C type cannot hold, such as
NAor2^31for a Cint, raises an error instead of being wrapped or rounded. - Rust crates annotated for UniFFI load with R bindings generated when the crate is built.
Installation
zuffi is not on CRAN yet. Install the development version from GitHub:
# install.packages("pak")
pak::pak("pedrobtz/zuffi")Usage
Open a library, declare the functions you need as C text, and call them from the handle. Here, the C maths library:
library(zuffi)
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m")
ffi_cdef(lib, "double cos(double); double ldexp(double x, int exp);")
lib$cos(0)
#> [1] 1
lib$ldexp(1.5, 4L)
#> [1] 24
lib$ldexp(1.5, 4.5)
#> Error:
#> ! argument 2 (`exp`) of `ldexp()` must be an integer for C `int`, not doubleThe last call is refused before it reaches C, because 4.5 is not an int. zuffi also handles pointers, structs, callbacks and headers; the Get started article shows them.
Learn more
- Get started: declarations, exact conversions, structs and memory, callbacks, and Rust crates.
- Reference: every function, with the C types it accepts.
To write new compiled code for R, use Rcpp or .Call(); zuffi is for libraries that already exist.