Getting r function args from Rcpp c++ function

两盒软妹~` 提交于 2020-01-30 08:43:04

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/55495461/getting-r-function-args-from-rcpp-c-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!