Learn R Programming

Rcpp (version 0.10.2)

exportAttribute: Rcpp::export Attribute

Description

The Rcpp::export attribute is added to a C++ function definition to indicate that it should be made available as an R function. The sourceCpp and compileAttributes functions process the Rcpp::export attribute by generating the code required to call the C++ function from R.

Arguments

name
Specify an alternate name for the generated R function (optional, defaults to the name of the C++ function if not specified).

Details

Functions marked with the Rcpp::export attribute must meet several conditions to be correctly handled:
  1. Be defined in the global namespace (i.e. not within a C++namespacedeclaration).
  2. Have a return type that is either void or compatible withRcpp::wrapand parameter types that are compatible withRcpp::as(see sections 3.1 and 3.2 of theRcpp-introductionvignette for more details).
  3. Use fully qualified type names for the return value and all parameters. However, Rcpp types may appear without the namespace qualifier (i.e.DataFrameis okay as a type name butstd::stringmust be specified fully).
If default argument values are provided in the C++ function definition then these defaults are also used for the exported R function. For example, the following C++ function: DataFrame readData( CharacterVector file, CharacterVector exclude = CharacterVector::create(), bool fill = true)

Will be exported to R as:

function (file, exclude = character(0), fill = TRUE)

Note that C++ rules for default arguments still apply: they must occur consecutively at the end of the function signature and unlike R can't rely on the values of other arguments.

See Also

sourceCpp and compileAttributes

Examples

Run this code
#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
int fibonacci(const int x) {

   if (x == 0) return(0);
   if (x == 1) return(1);
   
   return (fibonacci(x - 1)) + fibonacci(x - 2);
}

// [[Rcpp::export("convolveCpp")]]
NumericVector convolve(NumericVector a, NumericVector b) {

   int na = a.size(), nb = b.size();
   int nab = na + nb - 1;
   NumericVector xab(nab);
    
   for (int i = 0; i < na; i++)
      for (int j = 0; j < nb; j++)
         xab[i + j] += a[i] * b[j];
    
   return xab;
}

Run the code above in your browser using DataLab