| Title: | Call C and Rust Libraries from R Without Glue Code |
|---|---|
| Description: | Calls functions in shared libraries that were never built for 'R', with no wrapper code and no compiler on the user's machine. Functions are declared from their C declarations, or read from a header, and called through 'libffi'. 'Rust' crates annotated for 'UniFFI' load with bindings generated when the crate is built. Every conversion between an 'R' value and a C value is exact or raises an error. |
| Authors: | Pedro Baltazar [aut, cre, cph], Anthony Green [cph] (libffi, in src/vendor/libffi), Red Hat, Inc. [cph] (libffi, in src/vendor/libffi), libffi contributors [cph] (libffi, in src/vendor/libffi; see inst/COPYRIGHTS), Meta Platforms, Inc. and affiliates [cph] (zstd's headers, a test fixture in tests/testthat/headers), libuv project contributors [cph] (libuv's headers, a test fixture in tests/testthat/headers), Joyent, Inc. and other Node contributors [cph] (libuv's headers, a test fixture in tests/testthat/headers), Niels Provos [cph] (libuv's uv/tree.h, a test fixture in tests/testthat/headers) |
| Maintainer: | Pedro Baltazar <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.0.9000 |
| Built: | 2026-12-05 21:38:04 UTC |
| Source: | https://github.com/pedrobtz/zuffi |
C does not say what type an argument given through ... has, and libffi
must know it: on Apple arm64 such arguments are even passed differently
from named ones. So each one is typed at the call, lib$printf("%ld\n", ffi_arg(3, "long")), and an argument given without ffi_arg() is an
error rather than a guess (design §4.1).
ffi_arg(value, type)ffi_arg(value, type)
value |
The value, converted at the call by the rules of |
type |
A C type name, such as |
C promotes float to double, and bool, char, short and the
8- and 16-bit integer types to int, in a variadic call, so those types
are refused here: give the promoted type.
An object of class zuffi_arg.
ffi_arg(3, "long") ffi_arg("text", "const char *")ffi_arg(3, "long") ffi_arg("text", "const char *")
ffi_callback() makes a C function pointer that calls fun, for a C
function that takes one: a comparator for qsort(), a handler a library
keeps and calls later. It is made with libffi's closure API (design
§4.5).
ffi_callback(fun, type, lib = NULL, default = NULL)ffi_callback(fun, type, lib = NULL, default = NULL)
fun |
An R function, called with one argument per C parameter. |
type |
The C type of the function pointer, as text. |
lib |
|
default |
The value the callback returns when it cannot run |
type is the pointer's C type, as a header writes it:
"int (*)(const void *, const void *)", or the name of a typedef of
one that lib declares. Arguments reach fun as R values by the rules
of design §6: numbers and strings as R vectors, pointers as borrowed
zuffi_ptr objects (NULL for a null pointer), structs by
value as a copy, enums as zuffi_enum integers. What fun returns is
converted back exactly, or the conversion fails as a call's argument
would: a struct result may also be a named list, an enum result an
enumerator's name, and a string or pointer result stays valid until the
callback is next called.
Lifetime. Passing a callback to a call keeps it alive for that call.
A library that keeps the pointer and calls it later needs it for longer:
with lib, the callback lives until ffi_close() closes that library,
whatever happens to the R object; without it, the R object must be kept,
and a callback collected while C still holds its pointer crashes the
process. ffi_free() frees one at once. lib is also where the type
names in type are read.
Errors and other jumps. An error, an interrupt or a restart in
fun must not jump across the library's frames, which would corrupt the
process. So the callback returns default to the library instead, and
every later callback of the same call returns default without running
R; once the library has returned, the error (or the interrupt, or the
restart) carries on as it would have. The library itself keeps running
until it returns: qsort() finishes its sort with a comparator that
answers default. A library with a way to stop early needs default
set to the value that asks for it. A callback that fails outside any
call zuffi made, as when a library runs it from a finaliser, turns its
error into a warning of class zuffi_callback_warning and returns
default.
Threads. A callback runs R only on R's main thread. Called from
another thread, it returns default there without touching R, and the
next call zuffi makes from R raises a zuffi_thread_error that names it
(design D6).
Where the system refuses the executable memory a callback needs,
ffi_callback() raises a zuffi_closure_error and calls into C still
work; zuffi_info()'s closures says whether callbacks can be made.
A callback: a zuffi_ptr of class zuffi_callback, which a
call takes for a function-pointer argument. ffi_cast() to its type
makes an R function that calls it through C.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") 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 *)") x <- ffi_new(lib, "double[4]", c(3, 1, 4, 2)) lib$qsort(x, 4, 8, cmp) x[] ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") 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 *)") x <- ffi_new(lib, "double[4]", c(3, 1, 4, 2)) lib$qsort(x, 4, 8, cmp) x[] ffi_close(lib)
ffi_cdef() reads C declarations, as a header writes them, and binds
each function into the handle, so that lib$cos(0) calls the C
function cos. It reads functions, struct, union, enum and
typedef declarations with declarators of any depth, and #define
constants. It lays out structs as this platform's C compiler does,
honouring __attribute__((packed)), aligned(n) and #pragma pack, and
evaluates the integer constant expressions of array bounds and
enumerators, sizeof and casts included.
ffi_cdef(lib, text, errno = FALSE, annotate = list())ffi_cdef(lib, text, errno = FALSE, annotate = list())
lib |
A handle from |
text |
C declarations: one string, or lines that are joined. |
errno |
|
annotate |
What C's types cannot say (design §4.3): a list named
by function, each a list naming its arguments, with |
It does not preprocess: #include, #if and macros with arguments are
errors (ffi_include() runs a preprocessor first). Other compiler
extensions are read and ignored: attributes, __declspec, calling
conventions, __extension__, inline and the qualifiers. An
__asm__("name") label binds the declaration to that symbol.
What zuffi cannot lay out or call does not stop the declarations around
it (D12): a bit-field, _Complex, _Atomic, a vector type, a function
with a body, or long double by value makes that type or function
incomplete. A pointer to it still works; its size, its members or a
call raise a zuffi_unsupported_error that says why, and
ffi_functions() lists the reason.
Each enumerator and #define constant is bound into the handle too:
an integer when R's integers hold it, a double when a double holds it
exactly, a string for a string constant. One that R cannot hold
exactly raises an error when it is read; ffi_constants() lists
them. A function or constant
declared again replaces the earlier one; a type declared again must be
the same type. A function declared with () takes no arguments, as
(void), and a pointer to a function or to an array is a void *.
The declarations are read whole or not at all: an error, which gives the line and column, leaves the handle as it was.
lib, invisibly.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_cdef(lib, " double cos(double x); typedef struct { double re, im; } cplx; #define TWO_PI 6.283185307179586 ") lib$cos(lib$TWO_PI) ffi_sizeof(lib, "cplx") ffi_functions(lib) ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_cdef(lib, " double cos(double x); typedef struct { double re, im; } cplx; #define TWO_PI 6.283185307179586 ") lib$cos(lib$TWO_PI) ffi_sizeof(lib, "cplx") ffi_functions(lib) ffi_close(lib)
Lists the constants of a library handle: each enumerator and #define
constant that ffi_cdef() or ffi_include() bound into it, and each
macro that ffi_include() expanded and could not bind as a constant,
with why. A #define with a long double operand is never bound, on
any platform, and is listed as skipped by either function. It is the
counterpart of ffi_functions(); a bound constant's value is
lib$NAME.
ffi_constants(lib)ffi_constants(lib)
lib |
A handle from |
A data frame with one row per constant, in the order bound
(within one set of declarations, enumerators before #defines; a
constant bound again moves to the end, as a function declared again
does in ffi_functions()): name; kind, the constant's C
kind, "integer" (an integer constant or an enumerator, which R
holds as an integer or, past R's integers, as a double), "double"
(a floating constant) or "string", and NA for a macro that was
skipped; and reason, NA when lib$NAME gives the value, and
otherwise why not: the error reading it raises (a value R cannot hold
exactly), or why the macro was skipped. A macro that names a function
the handle declares is the function, and not listed.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_cdef(lib, " enum mode { READ = 1, WRITE = 2 }; #define TWO_PI 6.283185307179586 #define NAME \"zuffi\" #define HUGE_ID 9007199254740993 ") ffi_constants(lib) ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_cdef(lib, " enum mode { READ = 1, WRITE = 2 }; #define TWO_PI 6.283185307179586 #define NAME \"zuffi\" #define HUGE_ID 9007199254740993 ") ffi_constants(lib) ffi_close(lib)
ffi_dlopen() opens a shared library and returns its handle, an
environment into which declarations bind one R function per C function,
so that lib$f(x) calls f. ffi_dlsym() returns the address of a
symbol. ffi_close() unloads the library.
ffi_dlopen(name, version = NULL, path = NULL, int64 = c("double", "zuint")) ffi_dlsym(lib, symbol) ffi_close(lib)ffi_dlopen(name, version = NULL, path = NULL, int64 = c("double", "zuint")) ffi_dlsym(lib, symbol) ffi_close(lib)
name |
The library: a stem such as |
version |
For a stem, the version to open ( |
path |
Directories to search before the system's, or |
int64 |
How 64-bit integer results arrive: |
lib |
A handle from |
symbol |
The symbol's name. |
A name with a path separator, or with a library extension (.so,
.so.6, .dylib, .dll), is opened as given. Anything else is a stem,
and ffi_dlopen("zstd") looks for the platform's names:
Linux: libzstd.so, then the versioned libzstd.so.<n> files,
taking the highest version unless version pins one. The unversioned
name usually exists only where a -dev package is installed, and some
(libc.so, often libm.so) are linker scripts the loader refuses, so
the versioned name is the common case. The directories are those of
path, then LD_LIBRARY_PATH, then the loader's (/etc/ld.so.conf
and the system directories).
macOS: libzstd.dylib (libzstd.<version>.dylib with version),
in the directories of path, then DYLD_LIBRARY_PATH, then
DYLD_FALLBACK_LIBRARY_PATH, then /usr/local/lib and /usr/lib.
System libraries live in the dyld shared cache and open by these paths
though no file exists.
Windows: zstd.dll, then libzstd.dll (zstd-<version>.dll and
libzstd-<version>.dll with version), in the directories of path
and then the system directories.
The working directory is never searched. The handle records the path of the file that was opened and prints it.
The garbage collector never unloads a library, because one with running
threads or exit handlers can crash the process when unloaded; only
ffi_close() does. After it, every function of the handle raises a
zuffi_closed_error. ffi_close() refuses, with a zuffi_busy_error,
while a pointer whose free function is in the library is still owned
(see ffi_own()): it collects garbage once first, so a pointer nothing
refers to any more is freed rather than counted (design D11).
ffi_dlopen(): the handle, of class zuffi_lib.
ffi_dlsym(): a borrowed void * zuffi_ptr to the symbol, which
keeps the library reachable. ffi_close(): lib, invisibly.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") lib ffi_dlsym(lib, "cos") ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") lib ffi_dlsym(lib, "cos") ffi_close(lib)
A function declared with errno = TRUE has errno cleared before each
call and saved immediately after it, before R runs anything that could
change it; on Windows the same declaration saves GetLastError() too.
ffi_errno() and ffi_last_error() return the values the latest such
call saved.
ffi_errno() ffi_last_error()ffi_errno() ffi_last_error()
A library linked to a C runtime other than the one R uses has an errno
of its own, which zuffi cannot read.
ffi_errno(): an integer, 0 until a call has saved one.
ffi_last_error(): a double, NA on platforms other than Windows.
ffi_errno()ffi_errno()
Lists what ffi_cdef() declared in a library handle, with whether
zuffi can call each one and, if not, why (D12): a type it cannot pass,
a symbol the library does not export, a body it skipped.
ffi_constants() lists the constants.
ffi_functions(lib)ffi_functions(lib)
lib |
A handle from |
A data frame with one row per function, in the order declared:
name, signature (the declaration as C), callable (logical) and
reason (NA when callable).
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_cdef(lib, "double cos(double); int with_body(int x) { return x; }") ffi_functions(lib) ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_cdef(lib, "double cos(double); int with_body(int x) { return x; }") ffi_functions(lib) ffi_close(lib)
C's types do not say which pointer arguments a function reads, which it writes, how long a buffer is, or who frees a pointer it returns. These annotations say it, for the declarations they are given to (design §4.3).
ffi_in(len = NULL) ffi_out(len) ffi_inout(len = NULL) ffi_owned(free_fn)ffi_in(len = NULL) ffi_out(len) ffi_inout(len = NULL) ffi_owned(free_fn)
len |
For |
free_fn |
The name of the library function that frees the result. |
ffi_in(len): an R vector the function reads. For a non-const
pointer it is copied, so the function may write into the copy and the
vector stays as it was; a const pointer is passed with no copy.
ffi_out(len): a buffer the function fills. zuffi allocates len
elements, the function writes them, and the call returns them.
ffi_inout(len): an R vector copied into a buffer that the function
reads and writes; the call returns the buffer.
ffi_owned(free_fn): the result is a pointer that free_fn, a
function of the same library, frees: zuffi frees it when the pointer
is collected, or at ffi_free().
For ffi_in() and ffi_inout(), len names the argument that holds
the buffer's length: the caller no longer gives it, and zuffi passes the
vector's length. For ffi_out(), len is the number of elements, or
the name of the argument the caller gives it in. Lengths count
elements; bytes for void *.
A function with ffi_out() or ffi_inout() arguments returns a list:
value, its result, and one element per such argument. Buffers of
void, char, unsigned char and uint8_t come back as raw vectors,
the others as their type's R vector (design §6).
An annotation, of class zuffi_annotation.
ffi_out(len = "n") ffi_owned("free")ffi_out(len = "n") ffi_owned("free")
ffi_include() runs a C preprocessor over a header and gives the result
to the ffi_cdef() parser, so that the functions, types and constants
the header declares are bound into the handle. Includes, #if and
macros are expanded as the preprocessor expands them, with defines
set first.
ffi_include( header, lib, include = character(), defines = character(), annotate = list(), preprocessor = c("auto", "cc") )ffi_include( header, lib, include = character(), defines = character(), annotate = list(), preprocessor = c("auto", "cc") )
header |
The header: a path to a file, or a name such as
|
lib |
A handle from |
include |
Directories searched for headers, before the preprocessor's own. |
defines |
Macros defined before the header is read: a named
character vector, |
annotate |
As for |
preprocessor |
|
The preprocessor is the C compiler R builds packages with (R CMD config CC), run with -E, so ffi_include() needs a C toolchain: on Windows,
Rtools. preprocessor = "auto" would also use the c2mir preprocessor
of the zumir package, which needs no toolchain, once a release of it
offers one; none does yet, and without a compiler the error says so.
A header that includes only the compiler's own headers (<stddef.h>,
<stdint.h>, <limits.h>, <stdarg.h>, ...) needs nothing else; one
that includes the C library's headers (<stdio.h>, <pthread.h>) needs
them installed, and the error names the first header that is not.
Constants: each object-like macro that the header, or a file it
includes, defines is expanded and bound into the handle where the
parser can evaluate the expansion as an integer, floating or string
constant, as ffi_cdef() binds a #define. The rest (macros that
expand to a type, a function call or nothing) are skipped, and
ffi_constants() lists them with the reason.
The preprocessor's output is cached for the session, by header, include
directories, defines and preprocessor, and used again while no file
it read has changed.
What a header cannot say, annotate adds: which pointer arguments are
buffers and of what length, and which results the caller owns (see
ffi_in()).
The handle, invisibly.
zuffi_info() lists the preprocessors found.
if ("cc" %in% names(zuffi_info()$preprocessors)) { h <- tempfile(fileext = ".h") writeLines(c( "#include <stddef.h>", "#define ANSWER (6 * 7)", "typedef struct { size_t len; double x; } item;", "double cos(double);" ), h) lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_include(h, lib) lib$cos(0) lib$ANSWER ffi_sizeof(lib, "item") ffi_close(lib) }if ("cc" %in% names(zuffi_info()$preprocessors)) { h <- tempfile(fileext = ".h") writeLines(c( "#include <stddef.h>", "#define ANSWER (6 * 7)", "typedef struct { size_t len; double x; } item;", "double cos(double);" ), h) lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_include(h, lib) lib$cos(0) lib$ANSWER ffi_sizeof(lib, "item") ffi_close(lib) }
ffi_new() allocates zeroed memory for one value of a C type, fills in
what ... gives, and returns a pointer to it. The memory is held by R,
aligned for the type, and freed by R's garbage collector once nothing
refers to the pointer, or at once by ffi_free() (design §4.4).
ffi_new(lib, type, ...)ffi_new(lib, type, ...)
lib |
A handle from |
type |
A C type, as text: |
... |
The value, or the members by name. |
For a struct or union, ... gives members by name, as in a C
initialiser, and the rest stay zero; a member may be a nested struct,
given as a named list or as a pointer to one, or an array, given as a
vector. For a scalar, ... is one value; for an array type such as
"double[8]", one vector of at most that many elements. Each value is
converted exactly or raises an error, by the rules of design §6.
Members of the struct a pointer points to are read with p$x and
written with p$x <- value; elements of a buffer with p[i] and
p[i] <- value, counting from 1. Reads and writes are checked against
the size zuffi knows the memory has.
A zuffi_ptr to the new memory, r_owned, of known size.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") x <- ffi_new(lib, "double[3]", c(1, 2, 3)) x[2] x[2] <- 20 x[] ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") x <- ffi_new(lib, "double[3]", c(1, 2, 3)) x[2] x[2] <- 20 x[] ffi_close(lib)
ffi_sizeof() and ffi_offsetof() give what C's sizeof and
offsetof give, from zuffi's layout of the type for this platform's
ABI: padding, nesting, arrays, unions, and the packed, aligned and
#pragma pack attributes of a struct (design §4.2).
ffi_sizeof(lib, type) ffi_offsetof(lib, type, member)ffi_sizeof(lib, type) ffi_offsetof(lib, type, member)
lib |
A handle from |
type |
A C type, as text. |
member |
A member of a struct or union, as text; |
Types are C text, such as "int", "struct pt", "char *" or
"double[4]", and struct, union and typedef names are those declared
in the library handle. A type zuffi cannot lay out (a struct declared
without its members, or with a member it cannot lay out) raises a
zuffi_unsupported_error that says why.
A double: the size or offset in bytes.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_sizeof(lib, "double") ffi_sizeof(lib, "int[10]") ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") ffi_sizeof(lib, "double") ffi_sizeof(lib, "int[10]") ffi_close(lib)
uniffi_load() opens a library built from a Rust crate that uses
UniFFI 0.33, and evaluates the R
bindings that
uniffi-bindgen-r wrote for
it. It returns the crate's functions: m$f(x) calls the crate's f(), and
m$Thing_new() its object Thing's constructor new, whose result has
its methods (obj$method()).
uniffi_load(path, bindings = NULL, int64 = c("double", "zuint"))uniffi_load(path, bindings = NULL, int64 = c("double", "zuint"))
path |
The library: a path, or any name |
bindings |
The bindings' file, or |
int64 |
How 64-bit integers arrive, as in |
Build the crate as a cdylib (cargo build --release), then run
uniffi-bindgen-r on the library, which writes the bindings beside it,
named after the crate. That is where uniffi_load() looks by default: for
target/release/libmy_crate.so, target/release/my_crate.R
(my_crate.dll and my_crate.R on Windows). Rust and cargo are needed to
build the crate and the bindings, never to load them.
Before anything else is called, the library's UniFFI contract version and
every function's checksum are compared with the ones the bindings were
generated for. A library and bindings from different builds of the crate
refuse to load with a zuffi_contract_error naming the functions that
differ, rather than corrupting memory. zuffi reads contract version 33
(UniFFI 0.33) only.
How values cross, which Rust types are supported, and the classed
conditions a Rust error becomes, are in the design, §7.2 and §7.3.
Briefly: records are named lists, flat enums strings, enums with data
lists with a variant field, Option<T> NULL or the value, objects
environments whose Rust side is freed by the garbage collector or at once
by ffi_free(), and an Err a condition of class
c("<crate>_<Error>", "uniffi_error", "zuffi_error").
The bindings are R code, evaluated as source() would: load only files
you trust, as you would only load libraries you trust.
An environment, locked, holding the crate's functions and
constructors. The library's handle is in it as .lib; ffi_close()
refuses it while one of the crate's objects lives.
## Not run: # cargo build --release && uniffi-bindgen-r target/release/libmy_crate.so m <- uniffi_load("target/release/libmy_crate.so") m$add(1L, 2L) ## End(Not run)## Not run: # cargo build --release && uniffi-bindgen-r target/release/libmy_crate.so m <- uniffi_load("target/release/libmy_crate.so") m$add(1L, 2L) ## End(Not run)
What this build of zuffi has
zuffi_info()zuffi_info()
A list: version, zuffi's version; libffi, the vendored
libffi's version; target, the libffi target it was built for. Both
are NA where libffi has no target, and every call then raises a
zuffi_target_error (design §4.8); uniffi, the UniFFI contract
versions the runtime reads (33, UniFFI 0.33; design D9); closures,
whether this process can make callbacks now (ffi_callback()), which
needs executable memory the system may refuse (design §4.9);
preprocessors, the preprocessors ffi_include() can use here, a
named character vector (cc: the C compiler's command), empty when
there is none. Later versions add fields.
zuffi_info()zuffi_info()
A zuffi_ptr is a C pointer with the type it points to, the number of
bytes behind it when zuffi knows it, and who frees it (design §4.4):
ffi_cast(ptr, type) ffi_string(ptr, n = NULL, encoding = "UTF-8") ffi_own(ptr, free_fn) ffi_free(ptr)ffi_cast(ptr, type) ffi_string(ptr, n = NULL, encoding = "UTF-8") ffi_own(ptr, free_fn) ffi_free(ptr)
ptr |
A |
type |
The pointer type to view it as, such as |
n |
The number of bytes to read, or |
encoding |
How the bytes are text: |
free_fn |
A function of a library handle, declared with one pointer
argument, that frees what |
borrowed, the default for pointers C returns: zuffi never frees it;
owned, after ffi_own(ptr, free_fn) or a declaration's
ffi_owned(): free_fn frees it once, when the pointer is collected
or at ffi_free();
r_owned, memory from ffi_new() and structs that C functions
return by value: R's collector frees it.
ffi_cast() views the same address as another pointer type: C
declarations check the type a pointer points to, and void * accepts
any. ffi_string() copies the bytes at a pointer into an R string.
ffi_own() marks a borrowed pointer as owned, and ffi_free() frees a
pointer now, for memory that should not wait for a collection.
ffi_free() also releases a UniFFI object's handle now; using the object
afterwards is a zuffi_freed_error. It frees a callback from
ffi_callback() now too, which C must not call again.
ffi_cast() to a function-pointer type, such as "double (*)(double)",
gives an R function that calls the function at that address: a function
pointer a library returned, one from ffi_dlsym(), or a callback. It
keeps ptr, and refuses to call once ptr is freed.
A pointer freed through zuffi, by ffi_free() or its finaliser, is
cleared, and so is every pointer cast or derived from it: using one is a
zuffi_freed_error. A finaliser does nothing in a forked child, such as
one parallel::mclapply() starts, so a resource is released once; and
finalisers do not run when R exits. An owned pointer keeps its free
function's library loaded, and ffi_close() refuses while one is alive.
What zuffi cannot see, it cannot check: memory the library freed itself, a pointer the library keeps after the call, or reads past a size zuffi was never told. Those crash R as they would crash C.
ffi_cast(): a borrowed zuffi_ptr, or for a function-pointer
type an R function. ffi_string(): a string,
or a raw vector. ffi_own(): ptr, invisibly. ffi_free(): NULL,
invisibly.
lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") p <- ffi_new(lib, "unsigned char[6]", c(104L, 101L, 108L, 108L, 111L)) ffi_string(ffi_cast(p, "char *")) ffi_free(p) ffi_close(lib)lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m") p <- ffi_new(lib, "unsigned char[6]", c(104L, 101L, 108L, 108L, 111L)) ffi_string(ffi_cast(p, "char *")) ffi_free(p) ffi_close(lib)