--- title: "Get started with zuffi" description: "Open a library, declare its functions, see what refuses to convert, lay out a struct, pass an R function as a callback, read a header, and load a Rust crate." output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Get started with zuffi} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") # ffi_include() runs the C preprocessor R was built with; where there is # none, its chunk is shown but not run. has_cc <- "cc" %in% names(zuffi::zuffi_info()$preprocessors) # Where libffi has no target (Windows on ARM, WebAssembly), zuffi refuses # every call: the chunks that call C are shown but not run. has_target <- !is.na(zuffi::zuffi_info()$target) ``` ```{r setup} library(zuffi) ``` 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`. ```{r} lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") lib ``` Declarations 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. ```{r, eval = has_target} ffi_cdef(lib, "double cos(double); double ldexp(double x, int exp);") lib$cos(0) lib$ldexp(1.5, 4L) ffi_functions(lib) ``` ## 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. ```{r, error = TRUE, eval = has_target} lib$ldexp(1.5, 4) lib$ldexp(1.5, NA_integer_) ``` The 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 `$`. ```{r} ffi_cdef(lib, "typedef struct { int x, y; } pt;") p <- ffi_new(lib, "pt", x = 1L, y = 2L) p$y <- 5L p$y ffi_sizeof(lib, "pt") ffi_offsetof(lib, "pt", "y") ``` A 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 *`. ```{r, eval = has_target} 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[] ``` An 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. ```{r, eval = has_cc && has_target} 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) lib$ANSWER ffi_sizeof(lib, "cplx") ``` A 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](https://mozilla.github.io/uniffi-rs/) loads with the R bindings that [uniffi-bindgen-r](https://github.com/pedrobtz/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: ```sh cargo build --release uniffi-bindgen-r target/release/libregex_ffi.so # writes regex_ffi.R beside it ``` `uniffi_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: ```{r, eval = FALSE} 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](https://pedrobtz.github.io/zuffi/reference/index.html) lists every function.