[Rcpp-devel] Call ++ funtion into R function called in rcpp

bbonit at tin.it bbonit at tin.it
Sun Jan 4 10:59:23 CET 2015


Dear list first of all happy new year.
I have a question .. I would like to call rcpp function  (so c++ 
function) into 
R function (optim for example) 
called into rcpp. I had prototype an example code and post 
below.  (Using Rcpp::InternalFunction(&foo))
Is it correct the way I had used? There is another more efficient and 
safety way 
Thank You in advance list 
Best regards
Gianluca Bonitta


library(inline)

inc <- ' NumericVector foo(const Rcpp::NumericVector &x) { 
        return - pow(x,2);
                        } '
code<- '
   Rcpp:: NumericVector start(Sexp_start);
   Rcpp:: Environment stats("package:stats"); 
   Rcpp:: Function optim = stats["optim"];    
   Rcpp:: List Opt;

   Opt=optim(_["par"]     = start,
             _["fn"]      = Rcpp::InternalFunction(&foo),
             _["method"]  = "BFGS");
return Opt;
'
fun.cpp <- cxxfunction(signature( Sexp_start = "NumericVector"),
                                           code, 
                                           include    = inc,
                                           plugin     = "Rcpp" )
fun.cpp (Sexp_start=0.1)

#### R code ####
fun. <- function(x) x^2
optim(0.1,fun.,method  = "BFGS")


More information about the Rcpp-devel mailing list