[Rcpp-devel] Call C++ Function into R function called in Rcpp

bbonit at tin.it bbonit at tin.it
Sun Jan 4 10:56:59 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")  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150104/6c7f3600/attachment.html>


More information about the Rcpp-devel mailing list