Re: [Rd] How to call R from C

From: Romain Francois <romain_at_r-enthusiasts.com>
Date: Mon, 22 Nov 2010 18:04:28 +0100

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

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Mon 22 Nov 2010 - 17:06:42 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 22 Nov 2010 - 17:30:26 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive