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
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
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