extendr / rextendr

An R package that helps scaffolding extendr-enabled packages or compiling Rust code dynamically
https://extendr.github.io/rextendr/
Other
174 stars 25 forks source link

Exposing a complex struct from Rust to R #333

Closed vemonet closed 6 months ago

vemonet commented 6 months ago

Hi @Ilia-Kosenkov, thanks a lot for this really nice package! We are trying to define bindings to expose our rust package to R. Note that my knowledge of R is really low so sorry in advance if I am not using the right terms in R terminology

Our package is a converter that works in 2 steps:

  1. Load the converter from a file (typically a JSON file available at some URL)
  2. Use the loaded converter to convert a URI to a compressed URI (aka. CURIEs)

That would look like this in rust:

let converter = from_extended_prefix_map("http://some_url.com/extended_map.json")).await?;

let curie = converter.compress("http://my-uri.org")

rextendr seems our best option for this, but I could not find any documentation or example to expose a custom rust struct, I could only find examples for "1 shot" functions using common data types (string, int, float)

Do you know if it would be possible to use rextendr to expose our rust struct as a R class, and then call this R class to perform compress? If yes, is there any pointers to help us get started?

Or do we need to look for a less optimized solution? (e.g. I am thinking of putting the converter loading + compression in the same function, not ideal because it will need to reload the converter at each call of compress, but that seems the most straightforward)

Ilia-Kosenkov commented 6 months ago

Hi, thanks for your interest in the project. We do not support out-of-the-box async code, R is a single-threaded application, so you if you can synchronously wait for completion, it might work. There are more docs in extendr/extendr, here is an example of defining a custom struct and exposing it via an impl (the data is never stored in R directly, but you can read & modify state using $ operator). rust And here is its usage on the side of R R tests

Alternatively, if you want to return data to R, you can populate e.g. a List. (See more docs here)

Finally, we have a feature-gated support for serde, so if your data type is serde-compatible, you shuold be able to marshal it to and from R with little to no issues

We also have a discord, see contributing

Hope it helps!

vemonet commented 6 months ago

Thanks a lot @Ilia-Kosenkov ! Sorry I did not realized there was 2 packages extendr and rextendr!

extendr fits perfectly our needs