r - 使用 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 函数。
建议将不胜感激。
解决方案
一种可能的解决方案是将 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
推荐阅读
- python-3.x - pytest - 默认夹具参数值
- python - 导出到 Excel 时数据覆盖
- pandas - 使用 pandas 将函数应用于多列
- c# - Aspnetcore 2.2 以 .Net Framework 为目标,InProcess 在 azure app 服务上失败,并出现错误 TTP 错误 500.0 - ANCM In-Process Handler Load Failure
- node.js - Lambda 在与 DynamoDB 通信时开始随机超时
- reactjs - 如何使用 Jest 和 Enzyme 测试组件实例内部调用的方法
- java - 以编程方式更改颜色资源?
- jakarta-ee - WLST:部署共享库不起作用
- firebase - 大查询的 Firebase 性能数据
- javascript - 如何使用 Strophe.js 启用流管理?