Search code examples
c++rrcpp

Getting r function args from Rcpp c++ function


I have defined a function on the R-side like this:

foo <- function(arg1, arg2, arg3) {
    ...
}

and a function in c++ using Rcpp that gets the global environment and instantiates the R function to execute it from that function. Here is the code:

namespace Rcpp;
void myFunction() {
    ...
    Environment env = Environment::global_env();
    Function funct = env["foo"];
    ...
}

It works fine, but I would like to check that the R function has exactly 3 args. How can I get the number of args of the R function in the c++ method?


Solution

  • You can use the closure access macro FORMALS and the PreserveStorage member function get__() (Rcpp::Function is a derived class of Rcpp::PreserveStorage) to get the formals, then get its number of elements:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    int n_formals() {
        Environment env = Environment::global_env();
        Function funct = env["foo"];
        SEXP sexp_funct = funct.get__();
        SEXP funct_formals = FORMALS(sexp_funct);
        return Rf_length(funct_formals);
    }
    
    
    /*** R
    foo <- function(x, y) x + y
    n_formals()
    foo <- function(x, y, z) x + y + z
    n_formals()
    */
    
    # > foo <- function(x, y) x + y
    # 
    # > n_formals()
    # [1] 2
    # 
    # > foo <- function(x, y, z) x + y + z
    # 
    # > n_formals()
    # [1] 3