Search code examples
c++c++11templatesrcpp

Using `c++` class templates into `R`


It's my first time taking a look at how to write wrap functions that allow me to interface with a class template I have created in c++, and I have a few questions.

How do I use an Rcpp::depends attribute to declare dependencies on static libraries that I've created? I assume I'll need to specify a path somewhere, but all the examples here just refer to libraries that are well known.

What are my options for R types I can use when I try to use this stuff in an R session? I have c++ classes that not only contain some data, but they also have methods that process this data and change state. This example only seems to change on vector into another. Does anyone have any examples or suggestions on how this can be accomplished?

namespace Rcpp {

    namespace traits{

        // Defined wrap case
        template <typename T> SEXP wrap(const boost::numeric::ublas::vector<T> & obj){
            const int RTYPE = Rcpp::traits::r_sexptype_traits<T>::rtype ;

            return Rcpp::Vector< RTYPE >(obj.begin(), obj.end());
        };


    }
}

Solution

  • This is a very broad question, so I can only give some pointers that might help you:

    • The Rcpp::depends attribute is not meant for dependencies on external libraries but for other R packages. Those R packages might provide the libraries (e.g. RcppArmadillo or RcppEigen) or the necessary infrastructure to link with a system library (e.g. RcppGSL). The latter is achieved via plugins, c.f. RcppGSL::inlineCxxPlugin(). Plugins can also be used without an extra package, c.f. here.

    • If you want to maintain state within a C++ object, you have to consider its life-cycle. If it a singleton like object I like to use an anonymous namespace. Otherwise you can use Rcpp::XPtr to bring the C++ object to R. This can also be achieved using the RCPP_EXPOSED_CLASS macro, c.f. the "Extending Rcpp" vignette.

    • Rcpp modules might also be worth a look. See the corresponding vignette and the RcppRedis package for an example.