Writing bindings
Source: vignettes/technical-details.qmd
This vignette covers what Get started with jlbind leaves out, so read that first.
One library for all clients
jlbind compiles Julia code with JuliaC.jl. Clients share one library and one Julia runtime, so your client shares Julia dependency versions with every other client the user has installed. Keep your [compat] bounds as wide as your code allows, so that it resolves alongside them.
When clients conflict, users can choose between them, give one a private library, or use separate libraries. A private library has its own copy of the Julia runtime, which takes disk space and memory.
What use_jlbind() adds
-
inst/julia/, containing a Julia binding package named after the R package with aBindingssuffix (for example,MyPkgBindings), including an example function. -
R/jlbind-wrappers.R, with an R function for each Julia function the binding package declares. - An
.onLoad()inR/zzz.Rthat callsjlbind::bind_client(). - The
Config/jlbind,Imports: jlbindandSystemRequirements: Julia (>= 1.13)fields inDESCRIPTION. - A
.jlbind/directory for development builds, added to.Rbuildignoreand.gitignore.
If your package already defines .onLoad(), add jlbind::bind_client(pkgname) to the existing function yourself.
All clients are compiled into one library, so binding package names must be unique across all jlbind clients. The default, the R package name with a Bindings suffix, ensures this.
Writing @rcall declarations
The binding package is an ordinary Julia package. Add its dependencies with Pkg, from your package’s directory, and import them as usual:
julia --project=inst/julia -e 'using Pkg; Pkg.add("SomePackage")'@rcall declarations literally at the top level
jlbind finds @rcall declarations by scanning the source files, not by running them, so write them literally at the top level of the module.
Default values
A default in a declaration becomes the default of the generated R function. For example,
@rcall summarise(x::Vector{Float64}, probs::Vector{Float64} = [0.25, 0.75],
na::Union{Missing,Float64} = missing)::Vector{Float64}generates
summarise <- function(x, probs = c(0.25, 0.75), na = NA) ...A default can be any of these:
| Julia default | R default |
|---|---|
| A literal number or string | The same literal |
true, false
|
TRUE, FALSE
|
missing |
NA |
nothing |
NULL |
[1, 2], Float64[1, 2]
|
c(1, 2) |
["a", missing] |
c("a", NA) |
Float64[], String[], … |
numeric(0), character(0), … |
An empty vector names its element type, as in Int32[] or Bool[].
Development libraries
By default, build_library() writes the library to .jlbind/ in your package’s source directory. When you load the package with devtools::load_all(), jlbind uses this development library instead of the one created by install_library(). Once .jlbind/ exists, devtools::load_all() rebuilds it when your binding package’s files or your package’s version have changed since it was built.
A library that has loaded cannot be replaced, so the .jlbind/ library is used only if your package is the first jlbind client loaded in the R session. On Linux and macOS, build_library(private = TRUE) gives the development library its own copy of the Julia runtime, so it loads alongside the shared library whatever the order.
If you need to use a library stored elsewhere, set the JLBIND_LIBRARY environment variable to its path before loading the package.
You can also test against an unreleased version of a Julia dependency by providing a local checkout through develop:
jlbind::build_library(develop = "~/dev/SomePackage.jl")Include a Manifest.toml next to the binding package’s Project.toml with the Julia dependency versions known to compile with your package. CRAN’s policy asks that downloaded libraries be a fixed version rather than the latest.
The build uses the manifest of only the first client that has one (see When clients conflict), so keep your [compat] bounds accurate too.
Types
@rcall converts each argument using from_sexp() and converts the return value using to_sexp(). The built-in conversions are:
Single values
| Julia | R argument | R result |
|---|---|---|
String, Symbol
|
A single string | A character vector of length one |
Float64 |
A single number | A double |
Int64 |
A single whole number | A double |
Int32 |
A single whole number | An integer |
Int16, Int8, UInt16
|
A single whole number in range | An integer |
UInt32 |
A single whole number in range | A double |
Float32, Float16
|
A single number in range | A double |
Bool |
TRUE or FALSE
|
A logical |
ComplexF64 |
A single complex number | A complex |
Date |
A single Date
|
A Date
|
DateTime |
A single POSIXct
|
A POSIXct in UTC |
Union{Missing,T} |
A value of type T, or NA
|
A value of type T, or NA
|
Union{Nothing,T} |
NULL, or a value of type T
|
NULL, or a value of type T
|
Nothing |
NULL, invisibly |
Vectors and arrays
| Julia | R argument | R result |
|---|---|---|
Vector{String}, Vector{Symbol}
|
A character vector or factor | A character vector |
Vector{Float64}, Vector{Int64}
|
A numeric vector | A double vector |
Vector{Int32} |
A numeric vector of whole numbers | An integer vector |
| Vectors of the smaller types above | A numeric vector in range | An integer or double vector |
Vector{Bool} |
A logical vector | A logical vector |
Vector{ComplexF64} |
A complex or numeric vector | A complex vector |
Vector{UInt8} |
A raw vector | A raw vector |
Vector{Date} |
A Date vector |
A Date vector |
Vector{DateTime} |
A POSIXct vector |
A POSIXct vector in UTC |
Vector{Union{Missing,T}} |
A vector of type T, which can have NA |
A vector of type T with NA |
RVector{T} |
A double, integer or raw vector | The same vector |
Matrix{T}, Array{T,N}
|
A matrix or array of type T
|
A matrix or array of type T
|
Lists, data frames and references
| Julia | R argument | R result |
|---|---|---|
Other Vectors, Tuples |
A list | A list |
NamedTuple |
A named list, such as a data frame | A named list |
RDataFrame |
A data frame | A data frame |
Dict{String,T}, Dict{Symbol,T}
|
A named list | A named list, sorted by name |
RRef{T} |
A reference to a Julia object | A reference to a Julia object |
Vector{RRef{T}} |
A list of references | A list of references |
Conversion rules
-
Missing values:
NAis an error unless the type isUnion{Missing,T}orVector{Union{Missing,T}}, which turnNAintomissingand back. -
NaN: float and complex arguments accept it; other arguments reject it. -
Ranges: a number must fit its type, so an
Int16argument rejects40000. -
Int64results: these become doubles, since R’s integers have 32 bits. ReturnInt32for an R integer. -
Dates: to use
DateorDateTime, add theDatesstandard library to the binding package’s dependencies. -
Lists: if one element of a list can’t be converted, the error says which. For example, passing
list(c(1, 2), "a")as aVector{Vector{Float64}}gives the errorelement 2: expected a numeric vector.
Data frames
To take or return a data frame, wrap the columns in an RDataFrame. Its type lists the column names and the type of each column, so a type alias keeps signatures short:
const Sales = RDataFrame{(:group, :amount),Tuple{Vector{String},Vector{Float64}}}
const Summary = RDataFrame{(:group, :mean),Tuple{Vector{String},Vector{Float64}}}
function summarise(df)
gs = sort(unique(df.group))
means = [sum(df.amount[df.group .== g]) / count(==(g), df.group) for g in gs]
return RDataFrame((group = gs, mean = means))
end
@rcall summarise(df::Sales)::Summarysummarise(data.frame(group = c("a", "b", "a"), amount = c(1, 2, 3)))
#> group mean
#> 1 a 2
#> 2 b 2An RDataFrame argument:
- Must be a data frame (a tibble works too) with exactly the declared columns, in any order. If the data frame has other columns, select the ones you need in the R wrapper:
summarise(df[c("group", "amount")]). - Has its columns as properties (
df.group), andNamedTuple(df)returns them as a named tuple. - Converts each column by the usual rules, so a factor column arrives as strings, and a
Vector{Union{Missing,Float64}}column allowsNA.
Returning columns of different lengths is an error.
If you don’t need a data frame on the Julia side, a NamedTuple argument also accepts one, as a named tuple of its columns. It must have exactly the names of its fields, in any order.
Large vectors
Other conversions copy, so a function given a large vector it only reads can take an RVector{Float64} (or RVector{Int32}, RVector{UInt8}). That is an AbstractVector viewing R’s memory, without checking for NA. It is valid only until the call returns, so don’t store it.
Your own types
JLBind is jlbind’s own Julia package, which every binding package depends on, so write JLBind.foo as it is rather than with the name of your package.
A binding package can support additional types by defining methods for JLBind.from_sexp(::Type{T}, x::SEXP) and JLBind.to_sexp(x::T). JLBind also provides helpers for building R objects directly, such as JLBind.data_frame() for a data frame whose columns are not known when the library is compiled, and JLBind.alloc() and JLBind.alloc_matrix() for a vector or matrix to fill in place, without a copy in Julia first. The JLBind reference documents all of them.
By default, every client is compiled into the same library, so a pirated method of a JLBind function changes it for every client, and two clients pirating the same method fail to compile together. To convert a type you don’t own, wrap it in your own struct or open an issue to add it to JLBind.
Julia objects in R
Sometimes an object is better kept in Julia: it has no natural R equivalent, or it is large, such as a fitted model, and converting it on every call would be slow. You can pass such objects by reference using RRef{T}. R receives an external pointer to the Julia object, allowing it to be reused across calls. The object is released when R garbage-collects the reference, and jlbind::object_count() counts the objects R holds, to check that a package doesn’t leak them.
For example, define a mutable Julia object and expose functions that operate on it (the counterjl test client is a complete version of this):
mutable struct Counter
n::Int64
end
JLBind.r_class(::Type{Counter}) = "counter"
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)::Int64From R, you can create a counter and update it across calls:
counter <- new_counter(0)
class(counter)
#> [1] "counter"
increment(counter, 2)
#> [1] 2r_class() sets the R class of the external pointer, so your package can define methods such as print() for it. An argument declared as RRef{Counter} also checks that the reference points to a Counter, rather than accepting an arbitrary Julia object. A reference works with the library that made it, so with a client in a private library, its references work with that client’s functions only.
Saving Julia objects
R writes an external pointer as a null pointer, so by default a reference does not survive saveRDS(), save(), serialize(), or being sent to a parallel worker; using it afterwards gives an error. To make a type savable, you need to do two things.
In Julia, define JLBind.r_saved_by(), which names your R package, and JLBind.r_restore(), which rebuilds the object from the saved data:
JLBind.r_saved_by(::Type{Counter}) = "mypackage"
JLBind.r_restore(::Type{Counter}, state::SEXP) =
Counter(from_sexp(NamedTuple{(:n,),Tuple{Int64}}, state).n)
counter_value(c) = c.n
@rcall counter_value(c::RRef{Counter})::Int64In R, define .jlbind_saved_state(), which returns that data as a list of plain R values. It is internal, so don’t export it. If your package has several savable types, branch on the class of x:
.jlbind_saved_state <- function(x) {
list(n = counter_value(x))
}The first call that uses a loaded object rebuilds it, which needs the compiled library.
.jlbind_saved_state() only runs when saving, through an ALTREP vector in the reference’s jlbind_state attribute. Creating this vector adds about 400 ns to each new reference.
Errors
If a function called through @rcall throws a Julia exception, jlbind turns it into an R error. The messages from ArgumentError, ErrorException, DimensionMismatch, OverflowError, and AssertionError are passed through. Other exceptions are summarized.
Compilation constraints (trimming)
By default, jlbind compiles the shared library with juliac --trim=safe. This keeps the compiled image small by including only code reachable from the functions exposed through @rcall. It also requires calls to be resolvable at compile time.
If your package cannot be compiled with trimming, add the following field to DESCRIPTION:
Config/jlbind/trim: false
An untrimmed library includes the full Julia system image and is much larger, so avoid it if you can.
Abstract types
With trimming, a common source of compilation errors is a function that accepts several concrete types through an abstract RRef. Suppose your binding package works with shapes:
Shape types and their areas
abstract type Shape end
struct Circle <: Shape
radius::Float64
end
struct Square <: Shape
side::Float64
end
struct Rectangle <: Shape
width::Float64
height::Float64
end
struct Triangle <: Shape
base::Float64
height::Float64
end
JLBind.r_class(::Type{<:Shape}) = "shape"
area(s::Circle) = pi * s.radius^2
area(s::Square) = s.side^2
area(s::Rectangle) = s.width * s.height
area(s::Triangle) = s.base * s.height / 2An entrypoint that takes an RRef{Shape} knows only that its argument is some Shape. If it simply calls area(s), the compiler cannot tell which of the four methods that call reaches, and the build fails with an error such as:
Verifier error #1: unresolved call from statement area(s::Shape)::Any
The solution is to take the argument with @nospecialize and branch on the concrete types, making the call inside each branch, where the type is known. @narrow s (A, B, ...) expr does that: it evaluates expr with s narrowed to whichever of the listed types it is (see its reference):
circle(radius) = Circle(radius)
square(side) = Square(side)
rectangle(width, height) = Rectangle(width, height)
triangle(base, height) = Triangle(base, height)
shape_area(@nospecialize(s::Shape)) =
@narrow s (Circle, Square, Rectangle, Triangle) area(s)
scaled_area(@nospecialize(s::Shape), factor::Float64) =
@narrow s (Circle, Square, Rectangle, Triangle) factor^2 * area(s)
@rcall circle(radius::Float64)::RRef{Shape}
@rcall square(side::Float64)::RRef{Shape}
@rcall rectangle(width::Float64, height::Float64)::RRef{Shape}
@rcall triangle(base::Float64, height::Float64)::RRef{Shape}
@rcall shape_area(shape::RRef{Shape})::Float64
@rcall scaled_area(shape::RRef{Shape}, factor::Float64)::Float64Every shape can then be passed to the same generated R functions:
shapes <- list(circle(1), square(2), rectangle(2, 3), triangle(2, 3))
vapply(shapes, shape_area, numeric(1))
#> [1] 3.141593 4.000000 6.000000 3.000000
scaled_area(square(2), 3)
#> [1] 36A shape of a type that isn’t listed gives the error expected Circle, Square, Rectangle or Triangle; a fourth argument to @narrow is evaluated instead, to give another error or a default. List only the types the call has methods for.
Without @nospecialize, Julia compiles a separate shape_area for each concrete shape, and the call into it from the entrypoint can’t be resolved, for the same reason as area(s). A function that receives the shape and passes it on needs @nospecialize too.
If a hierarchy has only a few types, some alternatives to @nospecialize are:
Declare a separate entrypoint for each concrete type (
RRef{Circle},RRef{Square}, …) and choose between them in R.Use a small
Unionsuch asRRef{Union{Circle,Square}}, which Julia resolves by checking each member in turn.
Other calls that don’t compile
The same rule, that every call must resolve when the library is compiled, rules out a few common patterns:
-
Splatting a vector, as in
f(xs...)forxs::Vector: the number of arguments is only known at run time. Call a method that takes the vector, or callfonce per element if that gives the same result. -
Names of abstract types, as in
nameof(typeof(x))wherexis only known to be someShape. Use@narrowto give each type its name. -
Types as keyword arguments, as in
f(; type = T): the keyword arguments are stored in aNamedTuplewhose field is only aDataType. Pass the type positionally, or call the keyword form with@inlinewhereTis a constant.
Optional arguments are not a problem: @rcall calls the function in a separate branch for nothing (or missing) and for a value of each argument declared as a Union{Nothing,T} (or Union{Missing,T}), so each call has concrete types. This needs the Union written out in the declaration, not an alias for it.