Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building packages with Rcpp, Attributes not handled correctly

Tags:

r

rstudio

rcpp

I've been playing around with setting up an R package which aims to make use of Rcpp in RStudio, but I'm struggling to get things to work properly with Rcpp Attributes.

My understanding of how this works is fairly tenuous, but my understanding is as follows:

  1. In the source C++ files, you can add Rcpp Attributes, for example the tag // [[Rcpp::export]] marks a C++ function for exporting, making it available for R.
  2. When you do Build the package, Rcpp then generates the appropriate C++ code in the file RcppExports.cpp, and wrapper functions in the R source file RcppExports.R.

This doesn't seem to be working properly (as I expect) when I build my package. Roxygen isn't playing nicely with this when generating the NAMESPACE file (so i've disabled that). The tag // [[Rcpp::export]] seems to just mark the function for exporting to R, rather than also marking a function for being exported to the package Namespace.

More importantly, the Rcpp Attribute tag // [[Rcpp::depends()]] isn't being handled correctly. If I copy the code here into a new source file, and rebuild my package, gcc throws errors on the RcppExports.cpp file saying that the BigMatrix identifier is undeclared indicating that the attribute tage // [[Rcpp::depends(bigmemory)]] isn't being handled correctly.

Since multiple things aren't working as I would expect, What am I missing in my understanding of Rcpp Attribute tags?

like image 822
Scott Ritchie Avatar asked Aug 26 '13 06:08

Scott Ritchie


1 Answers

This is an issue with the RcppExports.cpp file that is generated. At the moment, there is no way to teach it to include header files from somewhere else, so it just does not include bigmemory/MatrixAccessor.hpp.

A workaround is to do this:

#include <Rcpp.h>
#include <bigmemory/MatrixAccessor.hpp>

Rcpp::NumericVector BigColSums(Rcpp::XPtr<BigMatrix> pBigMat) {

    // Create the matrix accessor so we can get at the elements of the matrix.
    MatrixAccessor<double> ma(*pBigMat);

    // Create the vector we'll store the column sums in.
    Rcpp::NumericVector colSums(pBigMat->ncol());
    for (size_t i=0; i < pBigMat->ncol(); ++i)
        colSums[i] = std::accumulate(ma[i], ma[i]+pBigMat->nrow(), 0.0);
    return colSums;
}

// [[Rcpp::export]]
Rcpp::NumericVector BigColSums( SEXP pBigMat ){
    return  BigColSums( Rcpp::XPtr<BigMatrix>( pBigMat) ) ;   
}

So that you capture the type in your .cpp file and RcppExports.cpp only has to know about SEXP.

like image 159
Romain Francois Avatar answered Sep 20 '22 04:09

Romain Francois