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.
Usage
ffi_cdef(lib, text, errno = FALSE, annotate = list())Arguments
- lib
A handle from
ffi_dlopen().- text
C declarations: one string, or lines that are joined.
- errno
TRUEto saveerrno(and on WindowsGetLastError()) after each call of the functions declared here, forffi_errno().- annotate
What C's types cannot say (design §4.3): a list named by function, each a list naming its arguments, with
ffi_in(),ffi_out()orffi_inout(), and.returnwithffi_owned().
Details
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.
Examples
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)
#> [1] 1
ffi_sizeof(lib, "cplx")
#> [1] 16
ffi_functions(lib)
#> name signature callable reason
#> 1 cos double cos(double x) TRUE <NA>
ffi_close(lib)