问题描述
我有一个来自下游库的 C 函数,我像这样在 C 中调用
I have a C function from a down-stream library that I call in C like this
result = cfunction(input_function)
input_function
是一个回调,需要有如下结构
input_function
is a callback that needs to have the following structure
double input_function(const double &x)
{
return(x*x);
}
其中 x*x
是用户定义的计算,通常要复杂得多.我想使用 Rcpp 包装 cfunction
以便 R 用户可以在任意 R 函数上调用它.
Where x*x
is a user-defined computation that is usually much more complicated. I'd like to wrap cfunction
using Rcpp so that the R user could call it on arbitrary R functions.
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})
并得到正确的结果.
The R user then might do rfunction(function(x) {x*x})
and get the right result.
我知道在 cfunction
中调用 R 函数会降低速度,但我认为我可以在稍后弄清楚如何传递编译函数.我只想让这部分工作.
I am aware that calling R functions within cfunction
will kill the speed but I figure that I can figure out how to pass compiled functions later on. I'd just like to get this part working.
我能找到的最接近我需要的是这个 https://sites.google.com/site/andrassali/computing/user-supplied-functions-in-rcppgsl 包装了一个函数,该函数使用回调函数,其中包含一个非常有用的第二个参数我可以填充 R 函数.
The closest thing I can find that does what I need is this https://sites.google.com/site/andrassali/computing/user-supplied-functions-in-rcppgsl which wraps a function that uses callback that has an oh-so-useful second parameter within which I could stuff the R function.
非常感谢您的建议.
推荐答案
一种可能的解决方案是将 R 函数保存到一个全局变量中并定义一个使用该全局变量的函数.我使用匿名命名空间使变量仅在编译单元内为人所知的示例实现:
One possible solution would be saving the R-function into a global variable and defining a function that uses that global variable. Example implementation where I use an anonymous namespace to make the variable known only within the compilation unit:
#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
这篇关于使用 rcpp 将 R 函数传递给 C 例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!