RCPP Extending
RCPP Extending
This note provides an overview of the steps programmers should follow to The Rcpp converter functions Rcpp::as and Rcpp::wrap are
extend Rcpp (Eddelbuettel et al., 2019a; Eddelbuettel and François, 2011) extensible to user-defined types and third-party types.
for use with their own classes. This document is based on our expe-
rience in extending Rcpp to work with the Armadillo (Sanderson, 2010)
2. Extending Rcpp::wrap
classes, available in the separate package RcppArmadillo (Eddelbuettel
et al., 2019b). This document assumes knowledge of Rcpp as well as The Rcpp::wrap converter is extensible in essentially two ways :
some knowledge of C++ templates (Abrahams and Gurtovoy, 2004). intrusive and non-intrusive.
namespace Rcpp {
3.1. Intrusive extension. As part of its template meta programming namespace traits {
dispatch logic, Rcpp::as will attempt to use the constructor of the
target class taking a SEXP. template <typename T> class Exporter{
public:
#include <RcppCommon.h>
Exporter(SEXP x) : t(x){}
inline T get() { return t; }
class Foo{
public:
private:
Foo();
T t;
};
// this ctor enables implicit Rcpp::as
}
Foo(SEXP);
}
}
This is the reason why the default behavior of Rcpp::as is to
// this must appear after the specialization, or
invoke the constructor of the type T taking a SEXP.
// specialization will not be seen by Rcpp types
Since partial specialization of class templates is allowed, we can
#include <Rcpp.h>
expose a set of classes as follows:
4. Summary
The Rcpp package greatly facilitates the transfer of objects between
R and C++. This note has shown how to extend Rcpp to either user-
defined or third-party classes via the Rcpp::as and Rcpp::wrap
template functions. Both intrusive and non-intrusive approaches
were discussed.
References
Abrahams D, Gurtovoy A (2004). C++ Template Metaprogramming: Concepts,
Tools and Techniques from Boost and Beyond. Addison-Wesley, Boston.
Eddelbuettel D, François R (2011). “Rcpp: Seamless R and C++ Integration.”
Journal of Statistical Software, 40(8), 1–18. URL http://www.jstatsoft.org/v40/
i08/.
Eddelbuettel D, François R, Allaire J, Ushey K, Kou Q, Russel N, Chambers J,
Bates D (2019a). Rcpp: Seamless R and C++ Integration. R package version
1.0.3, URL http://CRAN.R-Project.org/package=Rcpp.
Eddelbuettel D, François R, Bates D, Ni B (2019b). RcppArmadillo: Rcpp
integration for Armadillo templated linear algebra library. R package version
0.9.800.1.0, URL http://CRAN.R-Project.org/package=RcppArmadillo.
Sanderson C (2010). “Armadillo: An open source C++ Algebra Library for Fast
Prototyping and Computationally Intensive Experiments.” Technical report,
NICTA. URL http://arma.sf.net.