Search code examples
rrcpp

Do I need to protect input SEXP?


In Rcpp, when running Rf_length on an input SEXP, do I need to further protect the input?

For example:

Would the below code be considered safe practice within Rcpp or is there a preferred method?

IntegerVector test(SEXP x) {
  int n = Rf_length(x);
  IntegerVector out(n);
  return out;
}

Solution

  • I would not think so as you are not allocating which is the step that needs protection --- and here the object assigned is an int that does not need. The IntegerVector you do create already gets its automagically added protection.

    But you could also avoid the issue and write eg

    IntegerVector mytest(IntegerVector vec) {
      IntegerVector out(vec.length());
      return out;
    }
    

    depending on the type of input type you have. And if you do not know the type at entry you can still switch based on TYPEOF(mysexp) and do the above.

    But in sum, simple read-only accessors such as Rf_length can be considered safe. The Writing R Extensions manual has the full gory details. I try to minimize SEXP in interfaces as the added safety from Rcpp is 'A Good Thing (TM)'.