使用 rcpp 将 R 函数传递给 C 例程

Passing R functions to C routines using rcpp

我有一个来自下游库的 C 函数,我在 C 中这样调用它

result = cfunction(input_function)

input_function是一个回调,需要有如下结构

double input_function(const double &x)
{
  return(x*x);
}

其中 x*x 是用户定义的计算,通常要复杂得多。我想使用 Rcpp 包装 cfunction 以便 R 用户可以在任意 R 函数上调用它。

NumericVector rfunction(Function F){

  NumericVector result(1);

  // MAGIC THAT I DON'T KNOW HOW TO DO
  // SOMEHOW TURN F INTO COMPATIBLE input_funcion

  result[0] = cfunction(input_function);

  return(result);
  }

然后 R 用户可能会 rfunction(function(x) {x*x}) 并得到正确的结果。

我知道在 cfunction 内调用 R 函数会降低速度,但我想我可以在以后弄清楚如何传递编译函数。我只想让这部分工作。

我能找到的最接近我需要的东西是这个https://sites.google.com/site/andrassali/computing/user-supplied-functions-in-rcppgsl,它包装了一个使用回调的函数,它有一个非常有用的第二个参数,我可以在其中填充 R 函数。

不胜感激。

一个可能的解决方案是将 R-function 保存到全局变量中并定义一个使用该全局变量的函数。我使用匿名命名空间使变量仅在编译单元内已知的示例实现:

#include <Rcpp.h>

extern "C" {
    double cfunction(double (*input_function)(const double&)) {
        return input_function(42);
    }
}

namespace {
std::unique_ptr<Rcpp::Function> func;
}

double input_function(const double &x) {
    Rcpp::NumericVector result = (*func)(x);
    return result(0);
}


// [[Rcpp::export]]
double rfunction(Rcpp::Function F){
    func = std::make_unique<Rcpp::Function>(F);
    return cfunction(input_function);
}

/*** R
rfunction(sqrt)
rfunction(log)
*/

输出:

> Rcpp::sourceCpp('57137507/code.cpp')

> rfunction(sqrt)
[1] 6.480741

> rfunction(log)
[1] 3.73767