首页 > 解决方案 > 从 Rcpp c++​​ 函数获取 r 函数参数

问题描述

我在 R 端定义了一个函数,如下所示:

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

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

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

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

标签: c++rrcpp

解决方案


您可以使用闭包访问宏FORMALSPreserveStorage成员函数get__()Rcpp::Function是的派生类Rcpp::PreserveStorage)来获取形式,然后获取其元素数:

#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

推荐阅读