JLBind reference
Source: vignettes/articles/jlbind-reference.qmd
JLBind is the Julia package your binding package uses to talk to R. using JLBind gives you @rcall, @narrow, from_sexp, to_sexp, SEXP, RRef, RVector and RDataFrame; use the rest as JLBind.name.
Declaring entrypoints
@rcall
@rcall f(arg::T, ...)::RMake f callable from R. jlbind::update_entrypoints() writes a matching R function for each @rcall.
greet(name) = "Hello, " * name * "!"
@rcall greet(name::String)::StringEvery argument and the return value need a type, which decides how they are converted (see from_sexp and to_sexp). Use RRef{T} to give R a Julia object by reference. An argument of type Union{Nothing,T} accepts NULL, and Union{Missing,T} accepts NA.
An argument can have a default, which the R function gets too: a number, string, true, false, missing (NA), nothing (NULL), or a vector of these such as [1, 2].
If f throws, R gets an error. The message of an ArgumentError, error() and a few other common exceptions is passed on; others get a generic message.
Write each @rcall at the top level of a file, as update_entrypoints() reads the source.
Converting values
@rcall converts arguments and return values with these.
from_sexp
from_sexp(T, x::SEXP) -> TConvert the R object x to a T, or throw an ArgumentError saying what was expected. @rcall converts every argument with it; add a method to accept a type of your own.
It supports:
-
StringandSymbol(from a string or factor),Bool,Float64,Int64,Int32,ComplexF64,Date,DateTimeand the smaller number types, and vectors of all of these; -
Union{Missing,T}andVector{Union{Missing,T}}, which allowNA; -
Union{Nothing,T}, which allowsNULL; -
Matrix{T}andArray{T,N}, from an R matrix or array; - other
Vectors,Tuples,NamedTuples andDict{String,T}, from a list; -
RVector{T},RDataFrame, andSEXP, which is passed as is.
to_sexp
to_sexp(x) -> SEXPConvert x to an R object. @rcall converts every return value with it; add a method to return a type of your own.
It supports the types from_sexp does, plus nothing (NULL) and missing (NA). An Int64 becomes a double, since R’s integers have 32 bits: return an Int32 for an R integer.
RVector
RVector{T}A read-only view of the data of an R vector, without a copy: RVector{Float64} for a double vector, RVector{Int32} for an integer vector and RVector{UInt8} for a raw vector. Use it for a large vector you only read.
NA is not checked for, and the view is only valid during the call, so don’t keep it. Returning it returns the R vector it views.
RDataFrame
RDataFrame(columns::NamedTuple)A data frame, converted to and from an R data.frame (or tibble). Its columns are df.x and so on. As an argument, the data frame must have exactly these columns, in any order.
const Sales = RDataFrame{(:group, :amount),Tuple{Vector{String},Vector{Float64}}}
total(df) = sum(df.amount)
@rcall total(df::Sales)::Float64Julia objects in R
RRef
RRef{T}A Julia object that R holds by reference, for objects that are easier to keep in Julia than to convert:
new_counter(start) = Counter(start)
increment(c, by) = (c.n += by; c.n)
@rcall new_counter(start::Int64)::RRef{Counter}
@rcall increment(c::RRef{Counter}, by::Int64)::Int64R gets an object of class r_class(T) that it can pass back to any entrypoint taking an RRef{T}, and a Vector{RRef{T}} is a list of them. The Julia object is freed once R no longer uses it. A reference that is saved and loaded again has lost its object, unless the type supports saving (see r_saved_by).
If T is abstract, take the argument with @nospecialize and call methods on it with @narrow.
r_class
r_class(T) -> StringThe R class of references to Ts, "jlbind_ref" by default. Define a method to give them a class of their own, for methods such as print():
JLBind.r_class(::Type{Model}) = "mymodel"r_saved_by
r_saved_by(T) -> Union{String,Nothing}Return your package’s name to let references to Ts be saved with saveRDS() and the like. By default they can’t be: a reference that is saved and loaded again has lost its object.
Saving also needs an r_restore method, and an R function .jlbind_saved_state(x) in your package (it need not be exported) that returns a list to rebuild the object from:
JLBind.r_saved_by(::Type{Model}) = "mypackage"
JLBind.r_restore(::Type{Model}, state::SEXP) =
Model(from_sexp(NamedTuple{(:weights,),Tuple{Vector{Float64}}}, state).weights).jlbind_saved_state <- function(x) list(weights = model_weights(x))The object is rebuilt the first time a loaded reference is used. Supporting saving adds about 400 ns to creating each reference, and saveRDS(version = 2) can’t save one.
r_restore
r_restore(T, state::SEXP) -> TRebuild a T from the list .jlbind_saved_state() returned when it was saved (see r_saved_by). The list may come from an older version of your package, so check any version it records.
object_count
object_count() -> Int64How many Julia objects R holds references to, to check that they are freed.
Trimming
@narrow
@narrow x (A, B, ...) expr [otherwise]Evaluate expr with x known to be an A, a B, and so on, whichever it is. If it is none of them, evaluate otherwise, or throw an ArgumentError.
The compiled library needs this to call methods on an argument of an abstract type:
shape_area(@nospecialize(s::Shape)) = @narrow s (Circle, Square) area(s)Building R objects
To build a result yourself, without a copy, declare the entrypoint to return SEXP and use these, which call R’s C API directly. Most don’t check their arguments, so a wrong type or index crashes R instead of giving an error.
SEXP
SEXPAn R object, as R’s C API passes it. Declare an entrypoint to return SEXP to build its result yourself.
@R
@R(name)A function or variable of R’s C API, for ccall or cglobal:
ccall(@R(Rf_xlength), Int, (SEXP,), x)@r_global
@r_global(name)The value of one of R’s global SEXP variables, such as @r_global(R_NaString).
nil
nil() -> SEXPR’s NULL.
rtypeof, rlength
rtypeof(x::SEXP) -> Cint
rlength(x::SEXP) -> IntThe type of x (such as REALSXP), and its length.
NILSXP, LGLSXP, INTSXP, REALSXP, CPLXSXP, STRSXP, VECSXP, EXTPTRSXP, RAWSXP
NILSXP, LGLSXP, INTSXP, REALSXP, CPLXSXP, STRSXP, VECSXP, EXTPTRSXP, RAWSXPR’s object types, as rtypeof returns them and alloc takes them: NULL, logical, integer, double, complex, character and raw vectors, a list, and an external pointer.
NA_INTEGER, NA_REAL
NA_INTEGER, NA_REALR’s NA in an integer or logical vector, and in a double vector.
protect, unprotect
protect(x::SEXP) -> x
unprotect(n)Keep x from R’s garbage collector while you allocate other R objects, and release the last n objects protected, before returning. These are R’s PROTECT and UNPROTECT.
preserve, release
preserve(x::SEXP) -> x
release(x::SEXP)Keep x alive across calls, until it is released.
alloc, alloc_matrix
alloc(t, n) -> SEXP
alloc_matrix(t, nrow, ncol) -> SEXPA new R vector of type t and length n, or matrix of nrow rows and ncol columns, to fill in. protect it before allocating anything else.
mkchar
mkchar(s::Union{String,Symbol}) -> SEXPAn R string, the element of a character vector. Strings of symbols are cached, which makes returning many names faster.
string_elt, set_string_elt, vector_elt, set_vector_elt
string_elt(x::SEXP, i) -> SEXP
set_string_elt(x::SEXP, i, v::SEXP)
vector_elt(x::SEXP, i) -> SEXP
set_vector_elt(x::SEXP, i, v::SEXP)Get and set element i of a character vector or list. Indices start at 0, as in C, and aren’t checked. Make an element of a character vector with mkchar.
real_ptr, int_ptr, logical_ptr, complex_ptr, raw_ptr
real_ptr(x::SEXP) -> Ptr{Float64}
int_ptr(x::SEXP) -> Ptr{Cint}
logical_ptr(x::SEXP) -> Ptr{Cint}
complex_ptr(x::SEXP) -> Ptr{ComplexF64}
raw_ptr(x::SEXP) -> Ptr{UInt8}A pointer to the data of a double, integer, logical, complex or raw vector, to read with unsafe_load or fill with unsafe_store!. The type of x isn’t checked.
get_attrib, set_attrib
get_attrib(x::SEXP, name::SEXP) -> SEXP
set_attrib(x::SEXP, name::SEXP, value::SEXP)Get and set the attribute name of x, where name is an R symbol such as @r_global(R_NamesSymbol). A missing attribute is NULL.
data_frame
data_frame(names::Vector{String}, columns::Vector{SEXP}) -> SEXPAn R data.frame of the R vectors columns, for columns whose types are only known at run time. Keep the columns protected until the call returns. When the types are known, return an RDataFrame instead.