devtools::load_all()
import('source-file')

Foreign function interface

Modules don’t have a built-in foreign function interface yet but it is possible to integrate C++ code via the excellent Rcpp package.

Ad-hoc compilation

As an example, take a look at the rcpp module found under inst/doc; the module consists of a C++ source file which is loaded inside the __init__.r file:


Here’s the C++ code itself (the example is taken from the Rcpp documentation):


This module can be used like any normal module:

rcpp = import('rcpp')
ls(rcpp)
rcpp$convolve(1 : 3, 1 : 5)

Ahead-of-time compilation

Unfortunately, this has a rather glaring flaw: the code is recompiled for each new R session. In order to avoid this, we need to compile the code once and save the resulting dynamic library. There’s no straightforward way of doing this, but Rcpp wraps R CMD SHLIB.

For the time being, we manually need to trigger compilation by executing the __install__.r file found in the inst/doc/rcpp module path.

import('rcpp/__install__')

Once that’s done, the actual module code is easy enough:


We can use it like any other module:

compiled = import('rcpp/compiled')
compiled$convolve(1 : 3, 1 : 5)


klmr/modules documentation built on Feb. 3, 2021, 3:24 a.m.