R and D interop with saucer

bachmeier no at spam.net
Fri Jan 5 16:16:49 UTC 2024


On Saturday, 30 December 2023 at 00:50:54 UTC, data pulverizer 
wrote:

> That's a great point. I really can't remember what stage I was 
> writing saucer when I became aware of EmbedR, but one thing I 
> didn't understand was why it had to have pre-compiled weka? 
> code within the package this is the `R.lib` file, which is a 
> nonstarter security-wise. I also felt that such a project 
> should have strong syntactic similarities with Rcpp to 
> facilitate adoption, that it should have a nicer easier 
> interface, that it would be a good learning experience for me, 
> and that I could (probably) do a decent job at it.
>
> I have updated the package to include a reference to EmbedR 
> outlining these points. Interestingly enough, there is a Rust 
> package for R and D interop called embedr as well 
> (https://docs.rs/extendr-api/latest/extendr_api/).

Here is the updated version of embedr: 
https://github.com/bachmeil/embedrv2

The old version you're referencing is from ages ago. I don't know 
what you mean by Weka code. There was an old import library from 
when I tried to get embedding of R inside D to work on Windows.

The updated library generates the R bindings for the user. There 
might be something useful there, and the code isn't very long: 
https://github.com/bachmeil/embedrv2/blob/main/inst/embedr/r.d#L1228 There's an extern_R attribute to specify which functions to export to R.

Here's an example from the readme:

```
@extern_R ar1irf(double alpha, double shock, int h) {
	double[] result;
	result ~= shock;
	foreach(ii; 1..h) {
		result ~= alpha * result.last;
	}
	return result;
}
mixin(exportRFunctions);

double last(double[] v) {
	if (v.length > 0) {
		return v[$-1];
	} else {
		return 0.0;
	}
}
```

I honestly don't use D much as a replacement for Rcpp any longer. 
I mostly work in the other direction these days: 
https://bachmeil.github.io/betterr/ I've been adding Windows 
support lately so I can share my code with others.

There are possibly things in there that are useful to you 
(whether D calls R or R calls D is not relevant for working with 
the API). For instance, if you want to pass a function to R 
without creating a shared library (one example being an objective 
function for optimization): 
https://bachmeil.github.io/betterr/funcptr.html Another is using 
a custom allocator to pass data to R even if it was allocated in 
D: 
https://github.com/bachmeil/betterr/blob/main/testing/testalloc.d 
There are pieces of knowledge I gained by debugging segfaults, 
like the fact that certain operations will change the pointer of 
an array and that sort of thing.


More information about the Digitalmars-d-announce mailing list