Skip to contents

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

Usage

ffi_new(lib, type, ...)

Arguments

lib

A handle from ffi_dlopen(), whose struct, union, enum and typedef names, declared with ffi_cdef(), type may use.

type

A C type, as text: "int", "struct pt", "double[8]".

...

The value, or the members by name.

Value

A zuffi_ptr to the new memory, r_owned, of known size.

Details

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.

Examples

lib <- ffi_dlopen(if (.Platform$OS.type == "windows") "ucrtbase" else "m")
x <- ffi_new(lib, "double[3]", c(1, 2, 3))
x[2]
#> [1] 2
x[2] <- 20
x[]
#> [1]  1 20  3
ffi_close(lib)