[Rcpp-devel] can one modify array in R memory from C++ without copying it?

andre zege andre.zege at gmail.com
Wed Nov 2 01:59:51 CET 2011


Hi, guys. I have some pretty large arrays in R and i wanted to do some time
consuming modifications of these arrays in C++ without actually copying
them, just by passing pointers to them. Since i don't know internal data
structures of R, i am not sure it's possible, but i thought it was. Here is
some toy code that i thought should work, but doesn't. Maybe someone could
point out the error i am making

i have the following in the passptr.cpp to multiply array elements by 2
===============================
extern "C"{
 void modify(double *mem, int *nr, int *nc){
  for(int i=0; i< (*nr)*(*nc); i++)
    mem[i]=2*mem[i];
   }
}

----------------------------------------------
I compile it into a shared library using
R CMD SHLIB passptr.cpp
load and run from R as follows

--------------------------------

>dyn.load("/home/az05625/testarma/passptr.so")

>m<-matrix(1:10,nr=2)

>.C("modify", as.double(m), as.integer(2), as.integer(5), DUP=FALSE)



More information about the Rcpp-devel mailing list