[Rd] How to call R from C

Romain Francois romain at r-enthusiasts.com
Mon Nov 22 18:04:28 CET 2010


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



More information about the R-devel mailing list