Calling a C library from R usually means writing and compiling a wrapper for every function. zuffi skips that: you give it a function’s C declaration as text and call the function from R. On this page we use the C library every system has, the maths library, and take one handle to it from a first call to structs, callbacks and a header. At the end, the same handle idea loads a Rust crate.
Open a library and declare a function
ffi_dlopen() opens a shared library by path or by name
and returns a handle. On Windows the C runtime is
ucrtbase; elsewhere it is m.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m")
lib
#> <zuffi_lib> /usr/lib/x86_64-linux-gnu/libm.so.6
#> int64: double
#> 0 functionsDeclarations are C text, the same text a header holds, so you can
paste them. Each function ffi_cdef() declares becomes an R
function in the handle, and ffi_functions() lists them.
ffi_cdef(lib, "double cos(double); double ldexp(double x, int exp);")
lib$cos(0)
#> [1] 1
lib$ldexp(1.5, 4L)
#> [1] 24
ffi_functions(lib)
#> name signature callable reason
#> 1 cos double cos(double) TRUE <NA>
#> 2 ldexp double ldexp(double x, int exp) TRUE <NA>Exact or an error
A value the C type cannot hold exactly is refused before the call,
never rounded or wrapped. The most common surprise is that R’s numbers
are doubles: 4 is not an int, 4L
is.
lib$ldexp(1.5, 4)
#> Error:
#> ! argument 2 (`exp`) of `ldexp()` must be an integer for C `int`, not double
lib$ldexp(1.5, NA_integer_)
#> Error:
#> ! argument 2 (`exp`) of `ldexp()` is NA, which C `int` cannot representThe errors have the class zuffi_error, so code can catch
them, and nothing reached C. A double passed to a C float
rounds, the one conversion that may.
Structs and memory
Types are declared the same way. zuffi lays a struct out as the C
compiler for this platform would, and ffi_new() allocates
one in memory that R’s garbage collector frees. Its fields read and
write with $.
ffi_cdef(lib, "typedef struct { int x, y; } pt;")
p <- ffi_new(lib, "pt", x = 1L, y = 2L)
p$y <- 5L
p$y
#> [1] 5
ffi_sizeof(lib, "pt")
#> [1] 8
ffi_offsetof(lib, "pt", "y")
#> [1] 4A pointer such as p is a zuffi_ptr: it
knows its C type, its size and who frees it, so reading past its end is
an error, not a crash. Memory a C function allocates can be given an
owner with ffi_own().
Callbacks
Some C functions take a function pointer. ffi_callback()
turns an R function into one, given its C type. The C library’s
qsort() takes a comparator of two
const void *, which the R function reads by casting them to
double *.
ffi_cdef(lib, "void qsort(void *base, size_t n, size_t size,
int (*cmp)(const void *, const void *));")
cmp <- ffi_callback(function(a, b) {
x <- ffi_cast(a, "double *")[1]
y <- ffi_cast(b, "double *")[1]
as.integer(sign(x - y))
}, "int (*)(const void *, const void *)")
v <- ffi_new(lib, "double[5]", c(3, 1, 4, 1, 5))
lib$qsort(v, 5, 8, cmp)
v[]
#> [1] 1 1 3 4 5An error inside the callback does not jump through
qsort()’s frames: the callback returns its default to C,
qsort() finishes, and the error is raised in R once the
call has returned.
Headers
Rather than pasting declarations, ffi_include() reads a
header through the C preprocessor R was built with, and declares every
function, type and constant it finds. Here a small header of our own
stands in for a library’s.
h <- tempfile(fileext = ".h")
writeLines(c(
"#define ANSWER (6 * 7)",
"typedef struct { double re, im; } cplx;",
"double hypot(double, double);"
), h)
ffi_include(h, lib)
lib$hypot(3, 4)
#> [1] 5
lib$ANSWER
#> [1] 42
ffi_sizeof(lib, "cplx")
#> [1] 16A declaration zuffi cannot call, or a macro that is not a constant,
is listed with its reason by ffi_functions() and
ffi_constants() rather than stopping the rest.
Rust crates through UniFFI
A Rust crate annotated for UniFFI loads with the R
bindings that uniffi-bindgen-r
writes from the built library, so R compiles nothing. The generator is
not on crates.io yet; its repository says how to build it. For a crate
regex_ffi that exports a Regex object:
cargo build --release
uniffi-bindgen-r target/release/libregex_ffi.so # writes regex_ffi.R beside ituniffi_load() opens the library, finds the bindings
beside it, and checks that they match the library. The crate’s
functions, objects, records and errors arrive as R values. This chunk
needs that crate, so it is not run here:
re <- uniffi_load("target/release/libregex_ffi.so")
m <- re$Regex_new("[0-9]+")
m$find_all("a1b22c333") # c("1", "22", "333")Where next
-
?ffi_cdef: what a declaration may contain, and the annotations that make a pointer argument a buffer. -
?ffi_include: include directories, defines, and which preprocessor runs. -
?ffi_callback: what happens when a callback fails, or is called from another thread. -
?uniffi_load: the Rust types the bindings support. - The reference lists every function.