[Rcpp-devel] [Rd] Calling C++ from R

Dirk Eddelbuettel edd at debian.org
Fri Jan 21 14:38:25 CET 2011


On 21 January 2011 at 06:44, Douglas Bates wrote:
| It is more effective to send such inquiries to the Rcpp-devel mailing
| list which I am cc'ing on this reply.

Correct. 
 
| On Thu, Jan 20, 2011 at 3:05 PM, mtck1982 <xiaoch.sun at gmail.com> wrote:
| >
| > Hi All,
| >
| > I am new to this area and use Rcpp to call C++ from R and try to build the
| > package under Windows 7. I use Rtools and R 2.10.1 32bit. Everything works
| > fine with me, except using R functions like "rnorm" or "runif" in the C++
| > code. When I use "R CMD check" the package, it always return error
| >
| > ** libs
| >  making DLL ...
| > g++ -I"c:/PROGRA~2/R/R-210~1.1/include"
| > -I"c:/PROGRA~2/R/R-210~1.1/library/Rcpp/include"     -O2 -Wall  -c func.cpp
| > -o func.o
| > func.cpp: In function 'SEXPREC* myfunction(SEXPREC*, SEXPREC*)':
| > func.cpp:220: error: 'rgamma' was not declared in this scope
| > func.cpp:225: error: 'rnorm' was not declared in this scope
| > func.cpp:244: error: 'runif' was not declared in this scope
| > func.cpp:274: error: 'rbeta' was not declared in this scope
| > make: *** [func.o] Error 1
| >  ... don
| 
| It is not clear if you are trying to use the Rcpp "sugar"
| constructions, which can apply to entire vectors, of if you are using
| the functions in the R API.  If the latter then you will need to
| preface the name with Rf_, as in Rf_runif. Those are the actual names
| of the functions.  The Rinternals.h file defines a number of aliases,
| such as runif, but in Rcpp those aliases are turned off, so as to
| avoid name clashes.
| 
| You should note that when calling random number generator functions
| the programmer is responsible for getting and restoring the seed
| structure.  I can't remember the details right now and I am on a
| Windows system without the sources so I will rely on someone else to
| fill in the details.

The easiest is to just declared a variable of type 

    Rcpp::RNGScope

which saves state when entering the local scope (ie "set of curly braces")
and restores it when leaving, thanks to what one can do with C++. Here is
an example Romain wrote to the rcpp-devel list in October:

   In addition, we have the RNGScope class, whose constructor calls=20
   GetRNGstate and destruvctor calls PutRNGstate, so that you can do :

   fx <- cxxfunction( , '
           RNGScope scope ;
           NumericVector x = rgamma( 10, 1, 1 ) ;
           return x ;
   ', plugin="Rcpp" )

   fx()

That's self-contained example for inline, using the rgamma sugar function.
You need the Rcpp:: prefix or a 'using namespace Rcpp;' when you use that in
your own source code.

Dirk

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


More information about the Rcpp-devel mailing list