From romain at r-enthusiasts.com  Mon Nov 22 18:04:28 2010
From: romain at r-enthusiasts.com (Romain Francois)
Date: Mon, 22 Nov 2010 18:04:28 +0100
Subject: [Rd] How to call R from C
In-Reply-To: <dd613833191d1a0251af9399334f3f51@tweb20-2.nm>
References: <dd613833191d1a0251af9399334f3f51@tweb20-2.nm>
Message-ID: <4CEAA29C.5070601@r-enthusiasts.com>

Le 22/11/10 17:24, ??? a ?crit :
>
> Hi all!
> I read R Extensions manual.
> But still I am not sure how to call R functions from C.
> Would any of you give me a sample C code to show how to call R functions - for instance, time series functions - from C in the embedded way of C code?

As Brian said, there are plenty of examples to follow.

The basic idea is to create a call and evaluate it.

txt <- '
#include <R.h>
#include <Rdefines.h>

SEXP callrnorm(){
	SEXP call = PROTECT( lang2( install( "rnorm"), ScalarInteger(10) ) ) ;
	SEXP res = PROTECT( eval( call, R_GlobalEnv ) ) ;
	UNPROTECT(2) ;
	return res ;
}
'
writeLines( txt, "test.c" )
system( "R CMD SHLIB test.c" )
dyn.load( "test.so" )
.Call( "callrnorm" )



or using the inline package :

require(inline)
fx <- cfunction( , '
	SEXP call = PROTECT( lang2( install( "rnorm"), ScalarInteger(10) ) ) ;
	SEXP res = PROTECT( eval( call, R_GlobalEnv ) ) ;
	UNPROTECT(2) ;
	return res ;
' , verbose = TRUE)
fx()



And now for the Rcpp plug ;-) calling R functions is dramatically easy 
with Rcpp with the Rcpp::Function class.

require(inline)
fx <- cxxfunction( , '
	// grab the function
	Function rnorm("rnorm") ;

	// call it
	return rnorm(10, _["sd"] = 10) ;

' , plugin = "Rcpp" )
fx()


Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/9VOd3l : ZAT! 2010
|- http://bit.ly/c6DzuX : Impressionnism with R
`- http://bit.ly/czHPM7 : Rcpp Google tech talk on youtube



[Rd] How to call R from C
Romain Francois