[Rd] call R function from C code

Dirk Eddelbuettel edd at debian.org
Tue May 14 15:47:33 CEST 2013


If you are fine with another package doing the legwork for you, calling an R
function from C++ is very easy:

R> library(Rcpp)
R> cppFunction('NumericVector fun(NumericMatrix X, NumericVector y, Function s) { return s(X, y); }')
R> set.seed(42); solve(matrix(rnorm(9),3,3), rep(1,3))
[1] -0.778649  1.553893  0.717221
R> set.seed(42); fun(matrix(rnorm(9),3,3), rep(1,3), solve)
[1] -0.778649  1.553893  0.717221
R> 

So the C++ function 'fun' we created using Rcpp, and which just calls the
supplied function on the first two arguments, returns us the same answer from
C++ as we get when we call solve(X, y) in R.

Dirk

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



More information about the R-devel mailing list