Skip to contents

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.

Usage

ffi_include(
  header,
  lib,
  include = character(),
  defines = character(),
  annotate = list(),
  preprocessor = c("auto", "cc")
)

Arguments

header

The header: a path to a file, or a name such as "zstd.h" that the preprocessor finds in include or its own directories.

lib

A handle from ffi_dlopen(), or what ffi_dlopen() takes to open one.

include

Directories searched for headers, before the preprocessor's own.

defines

Macros defined before the header is read: a named character vector, c(NAME = "value"); "" defines one as empty.

annotate

As for ffi_cdef(): a list named by function, each a list naming its arguments, with ffi_in(), ffi_out() or ffi_inout(), and .return with ffi_owned().

preprocessor

"auto" or "cc", the system C compiler.

Value

The handle, invisibly.

Details

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

See also

zuffi_info() lists the preprocessors found.

Examples

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