Rcpp:从全局环境调用一个R函数,并在C++代码中使用它
Rcpp: call an R function from the Global Environment and use it in the C++ code
如何将不属于任何 R 包的 R 函数调用到C++代码中?我可以通过一个非常简洁的例子来告诉你我的意思。假设我有一个 R 文件,我在其中写入
myRfunction <- function(x){
return(x+2)
}
我想在通用 c++ 代码中使用它。所以,我写了类似的东西
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
arma::vec myCppfunction(arma::vec y){
arma::sec results = myRfunction(y); /* Or whatever I have to do to call it! */
return results;
}
有人可以告诉我怎么做吗?一般程序是什么?谢谢大家。
示例。在 R 中:
> timesTwoR <- function(x) 2*x
cpp
文件:
#include <Rcpp.h>
using namespace Rcpp;
Function timesTwoFromR = Environment::global_env()["timesTwoR"];
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return timesTwoFromR(x);
}
然后,在 R 中:
> timesTwo(42)
[1] 84
或者,可以将 R 函数作为参数传递给 C++ 函数,如下所示:
// [[Rcpp::export]]
NumericVector call_r_fun(NumericVector x, Function f) {
return f(x) ;
}
相关文章:
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 在函数内部的声明中初始化数组,并在外部使用它
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 定义C++新的环境变量并在 bat 文件中使用它
- Visual Studio 2017 停止工作,并在打开后显示许多控制台窗口
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 在 c++ 中模拟输入并在 JAVA 中读取它?
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 将通用对象传递给 Rust 并在使用后传递回 C++ 进行销毁
- 动态获取 esp32 的 mac 地址并在以太网库中使用它.
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 在C++的头文件中使用常量并在程序中询问其地址的任何潜在危险
- C++ 和 Boost.Python - 如何将变量公开给 python 并在循环中更新它?
- 如何在组合框中列出所有可用的 VCL 样式,并在组合框更改事件中应用该样式C++生成器?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 初始化类中的指针数组,并在另一个类中检索它