从 Rcpp C++ 函数获取 r 函数参数

Getting r function args from Rcpp c++ function

我在 R 端定义了一个这样的函数:

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

和一个使用 Rcpp 的 c++ 函数,它获取全局环境并实例化 R 函数以从该函数执行它。这是代码:

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

它工作正常,但我想检查 R 函数是否恰好有 3 个参数。如何在 C++ 方法中获取 R 函数的参数个数?

可以用closure access macro FORMALS and the PreserveStorage member function get__()Rcpp::FunctionRcpp::PreserveStorage的派生class)求形式,然后得到它的元素个数:

#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