首页 > 解决方案 > 使用 rcpp 将 R 函数传递给 C 例程

问题描述

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

result = cfunction(input_function)

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

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

哪里x*x是用户定义的计算,通常要复杂得多。我想cfunction使用 Rcpp 进行包装,以便 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})并获得正确的结果。

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

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

建议将不胜感激。

标签: rrcpp

解决方案


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

#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

推荐阅读