gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:06:13 25 4
gpt4 key购买 nike

我有一个来自下游库的 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})并得到正确的结果。

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

我能找到的最接近的东西就是这个 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

关于r - 使用 rcpp 将 R 函数传递给 C 例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com