[Rcpp-devel] About calling C/C++ functions in R

Dirk Eddelbuettel edd at debian.org
Wed Jun 16 03:14:03 CEST 2010


On 16 June 2010 at 08:13, xiagao1982 wrote:
| Dear friends,
|  
| I am a newcomer of Rcpp and RInside. I installed them in my system and
| successfully build the following example:
|  
| #include <RInside.h>                            //
|  for the embedded R via RInside
|  
| Rcpp::NumericMatrix createMatrix(const int n) {
|     Rcpp::NumericMatrix M(n,n);
|     for (int i=0; i<n; i++) {
|         for (int j=0; j<n; j++) {
|             M(i,j) = i*10+j; 
|         }
|     }
|     return(M);
| }
|  
| int main(int argc, char *argv[]) {
|     const int mdim = 4;                         // let the matrices be 4 by 4 
|     SEXP ans;
|     RInside R(argc, argv);                      //
|  create an embedded R instance 
|     
|     Rcpp::NumericMatrix M = createMatrix(mdim); //
|  create and fill a sample data Matrix 
|     R["M"] = M;                                 //
|  assign C++ matrix M to R's 'M' var
|     std::string evalstr = "\
|         cat('Running ls()\n'); print(ls());                    \
|         cat('Showing M\n'); print(M);                          \
|         cat('Showing colSums()\n'); Z <- colSums(M); print(Z); \
|         Z";                     // returns Z
|     ans = R.parseEval(evalstr);                 //
|  eval the init string -- Z is now in ans
|                                                 
|     Rcpp::NumericVector v(ans);                 //
|  convert SEXP ans to a vector of doubles
|     for (int i=0; i< v.size(); i++) {           // show the result
|         std::cout << "In C++ element " << i << " is " << v[i] << std::endl;
|     }
|     exit(0);
| }
|  
| Now I add a function in the C++ code:
|  
| const char* hello( std::string who ){

This defines a C++ function called "hello".

|     std::string result( "hello " ) ;
| result += who ;
|     return result.c_str() ;
| }
|  
| And I try to call this function in R:
|  
| std::string txt = "ret = hello('Friends'); print(ret);";

This calls an R function called "hello".

But as R != C++, it does not call the C++ function from above.

| R.parseEvalQ(txt);              // eval string quietly, no result
|  
| It fails to do that.
|  
| Could you please tell me how to achieve that? Thanks very much!

It is a bit more complicated than this. You probably want to start by reading
both the 'Writing R Extensions' manual and some of the introductory vignettes
for Rcpp. It can be done, but you need to do a little reading, experimenting
and learning first.

-- 
  Regards, Dirk


More information about the Rcpp-devel mailing list