Skip to contents

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):

Usage

ffi_cast(ptr, type)

ffi_string(ptr, n = NULL, encoding = "UTF-8")

ffi_own(ptr, free_fn)

ffi_free(ptr)

Arguments

ptr

A zuffi_ptr; for ffi_free(), also a UniFFI object.

type

The pointer type to view it as, such as "int *", "struct pt *" or "void *".

n

The number of bytes to read, or NULL to read up to the first NUL byte (no further than the pointer's known size).

encoding

How the bytes are text: "UTF-8", validated; "latin1", converted to UTF-8; or "raw", returned as a raw vector.

free_fn

A function of a library handle, declared with one pointer argument, that frees what ptr points to.

Value

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.

Details

  • 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.

Examples

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 *"))
#> [1] "hello"
ffi_free(p)
ffi_close(lib)