我已经在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函数的args数量?
最佳答案
您可以使用closure access macro FORMALS
和 PreserveStorage
member function 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