从Rcpp C ++函数获取R函数args [英] Getting r function args from Rcpp c++ function

查看:64
本文介绍了从Rcpp C ++函数获取R函数args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have defined a function on the R-side like this:

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

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

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"];
    ...
}

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

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?

推荐答案

您可以使用

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

这篇关于从Rcpp C ++函数获取R函数args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆