Rcpp:从全局环境调用一个R函数,并在C++代码中使用它



如何将不属于任何 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) ;
} 

相关内容

最新更新