c++ - 从 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 数量?
解决方案
您可以使用闭包访问宏FORMALS
和PreserveStorage
成员函数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
推荐阅读
- c# - 按钮未显示在gridview的末尾
- python - 关于在返回无的列表中查找子序列的代码
- excel - 在excel中按颜色求和
- javascript - 如何使用 Jquery 循环变量
- reactjs - 如何使TextField Material UI组件以白色文本和下划线开头
- php - 打印 html 图像标签不使用 php 渲染它
- html - 我想修复一个在父元素右下角有固定的元素
- c - 以链表的形式构建字典并获得分段错误(核心转储)错误
- java - 如何使用 Java 对 AWS S3 开发工具包的 getObject 方法进行单元测试?
- c++ - 为什么我的 C++ 代码中出现“未声明的标识符”错误?