Learning R Internals and C++
via Rcpp
Ren Qian
R Conference 2017, Beijing
sample code
// test.cpp
#include
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
> Rcpp::sourceCpp(file = "test.cpp")
> timesTwo(42)
[1] 84
let’s sneak into the tmp folder
> Rcpp::sourceCpp(file = "test.cpp", showOutput = TRUE, verbose = TRUE)
…
DIR: /tmp/RtmpNfgMZk/sourceCpp-x86_64-pc-linux-gnu-0.12.10/sourcecpp_16993188434b7
…
$ ls /tmp/RtmpNfgMZk/sourceCpp-x86_64-pc-linux-gnu-0.12.10/sourcecpp_16993188434b7/
sourceCpp_2.so
test.cpp test.cpp.R
test.o
test.cpp
// test.cpp
#include
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
/*** R
timesTwo(42)
*/
#include
// timesTwo
NumericVector timesTwo(NumericVectorx);
RcppExport SEXP sourceCpp_1_timesTwo(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(timesTwo(x));
return rcpp_result_gen;
END_RCPP
}
test.cpp.R
`.sourceCpp_1_DLLInfo`
0.12.10/sourcecpp_16993188434b7/sourceCpp_2.so')
timesTwo
rm(`.sourceCpp_1_DLLInfo`)
workflow
test.cpp (original)
Rcpp::sourceCpp
sourceCppContext
class
SourceCppDynlib
test.cpp
(generated)
R CMD SHLIB
compiling/linking
sourceCpp_2.so
dyn.load
.Call
src/attributes.cpp
C Interface for R in
{base}
/usr/share/R/include/
{R.h, Rinternals.h}
inst/include/Rcpp.h
-L/usr/lib/R/lib -lR
timesTwo (decorated)
sourceCpp_1_timesTwo
workflow
code generation
• attributes
• export
• depends
• plugin
• function wrapping
• input arguments
• output
• extern “C”
building
• compiler options
• include R and Rcpp
headers
• linker options
• linking with R
shared object
• artifac