Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing C++ class with Rcpp

Tags:

c++

r

rcpp

I've been playing around with Rcpp and a couple of questions are currently popping up...

From my understanding, if you want to expose a C++ class to R you need to write partial template specializations for Rcpp::wrap and Rcpp::as. I looked how this was done in the Rcpp::Date class and I have the following questions: - In Date.h we have:

// template specialisation for wrap() on the date
// OK as explained in docs for non intrusive 
// partial template specialization
template <> SEXP wrap<Rcpp::Date>(const Rcpp::Date &date);

Further down the header you have the following code:

template<> inline SEXP wrap_extra_steps<Rcpp::Date>( SEXP x ){
Rf_setAttrib( x, R_ClassSymbol, Rf_mkString( "Date" ) ) ;
return x ;
}

What is the wrap_extra_steps supposed to do? Is it required? Also in Date.cpp wrap method is implemented as follows:

template <> SEXP wrap(const Date &date) {
   return internal::new_date_object( date.getDate() ) ;
}

With the internal::new_date_object implemented as:

SEXP new_date_object( double d){
   SEXP x = PROTECT(Rf_ScalarReal( d ) ) ;
   Rf_setAttrib(x, R_ClassSymbol, Rf_mkString("Date"));
   UNPROTECT(1);
   return x;
}

OK I understand that an SEXP is created and returned to R, but I don't get the whole part with PROTECT(), Rf_setAttrib, UNPROTECT...what's happening here?

Thanks!

like image 502
BigONotation Avatar asked Nov 02 '22 22:11

BigONotation


1 Answers

There is an entire vignette discussing how to write as<>() and wrap()---the Rcpp-extending vignette.

As it discusses, partial specialization is just one of three approaches, and there are other example packages too. Date() is something Rcpp itself implements, so it is not the best example. Read the vignette, study other examples and ask on rcpp-devel.

like image 76
Dirk Eddelbuettel Avatar answered Nov 11 '22 22:11

Dirk Eddelbuettel