Package Setup
A ‘Hello, world!’ Example.
Once you have Rust and {rextendr}
installed, you can begin creating Rust-powered R packages.
The first step to using extendr is to create an R package. It is recommend to create a new package using the package {usethis}
.
::create_package("hellorust") usethis
If you are in the RStudio IDE, a new R project will be opened up for you with the file structure of a new R package.
.
├── DESCRIPTION
├── NAMESPACE
├── R
└── hellorust.Rproj
Now that you have a new R package, you can add extendr to it.
::use_extendr() rextendr
This will add an extendr package template to the R packge. We will go through the package structure in more depth shortly.
.
├── DESCRIPTION
├── NAMESPACE
├── R
│ └── extendr-wrappers.R
├── hellorust.Rproj
└── src
├── Makevars
├── Makevars.ucrt
├── Makevars.win
├── entrypoint.c
├── hellorust-win.def
└── rust
├── Cargo.toml
└── src
└── lib.rs
Inside of the file src/rust/src/lib.rs
is a hello world function.
/// Return string `"Hello world!"` to R.
/// @export
#[extendr]
fn hello_world() -> &'static str {
"Hello world!"
}
Note that roxygen2 can be used with Rust documentation comments ///
instead of //
.
The function is made available to R via the macro extendr_module!
.
// Macro to generate exports.
// This ensures exported functions are registered with R.
// See corresponding C code in `entrypoint.c`.
extendr_module! {
mod hellorust;
fn hello_world;
}
Use the function rextendr::document()
to automatically create R function wrappers to call the Rust function. This will recompile the Rust library.
::document()
rextendr#> rextendr::document()
#> ✔ Saving changes in the open files.
#> ℹ Generating extendr wrapper functions for package: hellorust.
#> ℹ Re-compiling hellorust (debug build)
#> .... truncated ....
#> ─ DONE (hellorust)
#> ✔ Writing 'R/extendr-wrappers.R'
#> ℹ Updating hellorust documentation
#> Writing NAMESPACE
#> ℹ Loading hellorust
#> Writing NAMESPACE
#> Writing hellorust-package.Rd
#> Writing hello_world.Rd
The file R/extendr-wrappers.R
was updated and now contains
#' Return string `"Hello world!"` to R.
#' @export
<- function() .Call(wrap__hello_world) hello_world
Run devtools::load_all()
to make the function available to your session.
::load_all()
devtools#> ℹ Loading hellorust
The package hellorust
has been loaded and now you can run hello_world()
hello_world()
#> "Hello world!"