Getting r function args from Rcpp c++ function

前端 未结 1 416
既然无缘
既然无缘 2021-01-23 18:42

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

相关标签:
1条回答
  • 2021-01-23 19:00

    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
    
    0 讨论(0)
提交回复
热议问题