简体   繁体   English

如何在 Rcpp/C++ 中将函数作为参数传递?

[英]How to pass in functions as arguments in Rcpp / C++?

I'm trying to write a function which can take in functions as its arguments in Rcpp.我正在尝试编写一个函数,该函数可以将函数作为 Rcpp 中的参数。 I have written an example function in R that shows the kind of functionality that I'm aiming for:我在 R 中编写了一个示例函数,它显示了我想要的功能类型:

simulate_and_evaluate <- function(simulate, evaluate) {
  y <- simulate(1)
  eval <- evaluate(y)
  return(eval)
}

simulate_fun <- function(n) rnorm(n, 0, 1)
evaluate_fun <- function(x) dnorm(x, 0, 1)

simulate_and_evaluate(simulate = simulate_fun,
                      evaluate = evaluate_fun)

In this function simulate_and_evaluate , this takes in two arguments which are both functions, one that simulates a number and one that evaluates a function with this simualted number.在这个函数simulate_and_evaluate ,它接受两个都是函数的参数,一个模拟一个数字,一个用这个模拟数字计算一个函数。 So as an example, we can simulate a value from a standard normal and evaluate the density of a standard normal at that point.例如,我们可以从标准法线模拟一个值,并评估该点标准法线的密度。 Does anyone know if there's a way to do this in Rcpp?有谁知道在 Rcpp 中是否有办法做到这一点?

Rcpp aims for seamless interfacing of R and C++ objects. Rcpp 旨在实现R 和 C++ 对象的无缝接口。 As functions are first class R objects represented internally as a type a SEXP can take, we can of course also ship them with Rcpp.由于函数是在内部表示为SEXP可以采用的类型的第一类 R 对象,因此我们当然也可以它们与 Rcpp 一起发送。 There are numerous examples.有很多例子。

So here we simply rewrite your function as a C++ function:所以在这里我们简单地您的函数重写为 C++ 函数:

Rcpp::cppFunction("double simAndEval(Function sim, Function eval) {
  double y = as<double>(sim(1));
  double ev = as<double>(eval(y));
  return(ev);
}")

And we can then set the RNG to the same value, run your R function and this C++ function and get the same value .然后我们可以将 RNG 设置为相同的值,运行您的 R 函数和这个 C++ 函数并获得相同的值 Which is awesome.这太棒了。

R> set.seed(123)
R> simulate_and_evaluate(simulate = simulate_fun,
+ evaluate = evaluate_fun)
[1] 0.341
R> set.seed(123) # reset RNG
R> simAndEval(simulate_fun, evaluate_fun)
[1] 0.341
R> 

But as @MrFlick warned you, this will not run any faster because we added no compiled execution of the actual functions we are merely calling them from C++ rathern than R.但是正如@MrFlick 警告你的那样,这不会运行得更快,因为我们没有添加实际函数的编译执行,我们只是从 C++ 而不是 R 调用它们。

The topic has been discussed before.这个话题之前已经讨论过了。 Please search StackOverflow, maybe with a string [rcpp] Function to get some meaningful hits.请搜索 StackOverflow,也许用一个字符串[rcpp] Function来获得一些有意义的命中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM