Rcpp-package {Rcpp} | R Documentation |
The Rcpp package provides C++ classes that
greatly facilitate interfacing C or C++ code in R packages using
the .Call
interface provided by R.
Detailed information is provided in the vignette ‘RcppAPI’ that
can be invoked from R via vignette("RcppAPI")
.
Rcpp provides matching C++ classes for a large number of basic R data types. Hence, a package author can keep his data in normal R data structure without having to worry about translation or transfer to C++. At the same time, the data structures can be accessed as easily at the C++ level, and used in the normal manner.
The mapping of data types works in both directions. It is as straightforward to pass data from R to C++, as it is it return data from C++ to R. The following two sections list supported data types.
Standard R datatypes that are understood are
Standard C++ datatypes can be returned to R in a named list, the most general data type in R. Permissible components of the returns list are the following C++ types:
Rcpp provides a header file and a library inside the installed
package in the directory lib
. From within R, you can compute
the directory location via system.file("lib", "Rcpp.h",
package="Rcpp")
. For Windows, it will be a static library
‘Rcpp.a’. For Linux and Mac OS X, it will be ‘libRcpp.so’.
To use Rcpp
in another package, you need to include the header
during compilation. This typically requires use of the -I
to
provide the location as in -I/usr/local/lib/R/site-library/Rcpp/lib
.
Similarly, for linking we need to provide the location of the library
via -L
as well as the actual library. An example for Linux
would be -L/usr/local/lib/R/site-library/Rcpp/lib -lRcpp
.
In order to make it more convenient to use Rcpp
, functions
providing these arguments were added. To use these, simply use a file
src/Makevars
such as this (which was taken from the
emdL1
package)
# compile flag providing header directory containing Rcpp.h PKG_CXXFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'` # link flag providing libary as well as path to library, and optionally rpath PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'`
Alternatively, one can also encode the test for these variables using
the GNU autoconf
system. The RQuantLib
package
provides an example of that.
Lastly, on Linux, and during development, it can convenient to simply
provide these files via soft links (or copies) from the usual locations like
‘/usr/local/include’ and ‘/usr/local/lib’ which
alleviates the need for explicit location flags like ‘-I’ or
‘-L’. Remember to also run ldconfig
after creating the
link for the library. Alternatively, you can hardcode the dynamic
library location using the rpath
linker directive:
Use on Windows is identical to the use in Linux. However only a static
library is provided. The two Rcpp
functions detailed
above provide the relevant content.
Dominick Samperi wrote most of Rcpp during 2005 and 2006. Dirk Eddelbuettel made some additions, and became maintainer in 2008.