extendr - A safe and user friendly R extension interface using Rust.

Extendr is a Rust extension mechanism for R

The following code illustrates a simple structure trait which is written in Rust. The data is defined in the struct declaration and the methods in the impl.

use extendr_api::prelude::*;

struct Person {
    pub name: String,
}

#[extendr]
impl Person {
    fn new() -> Self {
        Self { name: "".to_string() }
    }

    fn set_name(&mut self, name: &str) {
        self.name = name.to_string();
    }

    fn name(&self) -> &str {
        self.name.as_str()
    }
}

#[extendr]
fn aux_func() {
}


// Macro to generate exports
extendr_module! {
    mod classes;
    impl Person;
    fn aux_func;
}

The #[extendr] attribute causes the compiler to generate wrapper and registration functions for R which are called when the package is loaded.

On R’s side, users can access to the above Rust functions as follows:

# call function
aux_func()

# create Person object
p <- Person$new()
p$set_name("foo")
p$name()   # "foo" is returned

The extendr_module! macro lists the module name and exported functions and interfaces.

This library aims to provide an interface that will be familiar to first-time users of Rust or indeed any compiled language.

Anyone who knows the R library should be able to write R extensions.

Goals of the project

Where possible, we convert parameters to Rust native objects on entry to a function. This makes the wrapped code clean and dependency free. We aim to support writing idiomatic Rust code, with a minimum amount of markup.

#[extendr]
pub fn my_sum(v: &[f64]) -> f64 {
    v.iter().sum()
}

You can interact in more detail with R objects using the RObj type which wraps the native R object type. This supports a large subset of the R internals functions, but wrapped to prevent accidental segfaults and failures.

  • Extendr logo

License

Dev status

  • Github Actions Build Status
  • Crates.io
  • Documentation
  • License: MIT

Developers

  • Andy Thomason
    Author, maintainer
  • Mossa M. Reimert
    Author
  • Claus O. Wilke
    Author
  • Hiroaki Yutani
    Author
  • Ilia Kosenkov
    Author
  • Daniel Falbel
    Author
  • Genomics Plc
    Copyright holder