Skip to content
Prev 10338 / 10988 Next

[Rcpp-devel] RInside: C/C++ function(s) passed to R?

Le 08/11/2019 à 11:06, LEVRA-JUILLET William a écrit :
Sorry for a late comment but for what it's worth, XPtr won't help here 
as optim() expects an R function, not C++ pointer to a function. 
Moreover, this R function takes only one argument -- a vector, not a 
couple of scalars. So maybe you meant something similar to:
#include <RInside.h>
int main(int argc, char *argv[]) {
    RInside R(argc, argv);
    R.parseEval("Rcpp::cppFunction('double Banana(double x, double y) 
{return (1-x)*(1-x)+100*(y-x*x)*(y-x*x);};', cacheDir='lib')");
    R.parseEval("fn <- function(p, ...) Banana(p[1L], p[2L])");
    Rcpp::RObject res = R.parseEval("optim(c(-2,-2), fn)");
    Rf_PrintValue(res);
    return 0;
}

which prints:

$par
[1] 0.9990277 0.9977136

$value
[1] 1.269722e-05

$counts
function gradient
      157       NA

$convergence
[1] 0

$message
NULL

As already underlined by others this is a sub-optimal way to use C++ 
functions in R but here it is imposed by optim() interface. For better 
designed interfaces (at least from "optimality of R/C++ exchanges" point 
of view) refer to examples cited by Dirk and Inaki.

Best,
Serguei.