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

Dirk Eddelbuettel edd at debian.org
Sun Jan 4 16:29:15 CET 2015


On 4 January 2015 at 10:56, bbonit at tin.it wrote:
| 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

The RcppDE package goes about this in another way and leaves out the R side.
It offers an (evolutionary) optimization algorithm (via a C++ rewrite of what
DEoptim had at the time in C) which permits you to supply C++ functions to
optimize over.  It was a good exercise, and the ability to pass around
user-supplied C++ functions is a nice Rcpp trick.  (I now need to update
RcppDE to the current code in DEoptim....)

What you suggest below is probably doable, but probably of little interest as
you may spend too much time (in aggregate) going back and forth between
between R and C++.

So if I were you, I'd rather go to a decent optimization package available at
the C++ level --- as for example nlopt which happens to be available in R and
on CRAN via the nloptR package for which I helped Jelper a little with the
packaging logic --- and access the C++ optimization algoritms directly. 

Dirk


| 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") 
| 
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

-- 
http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org


More information about the Rcpp-devel mailing list