[Rcpp-devel] can one modify array in R memory from C++ without copying it?
Dirk Eddelbuettel
edd at debian.org
Wed Nov 2 02:24:46 CET 2011
On 1 November 2011 at 20:59, andre zege wrote:
| 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)
|
| From reading docs i thought that DUP=FALSE would ensure that R matrix is not
| copied and is multiplied by 2 in place. However, it's not the case, matrix m is
| the same after calling .C("modify"...)
|
| as it was before. Am i calling incorrectly, or is it just impossible to modify
| R matrix in place from C++? Would greatly appreciate any pointers.
Please ask basic R programming questions on R-devel as you seem to have read
the wrong documentation --- there is no support for .C() in Rcpp. We do what
we do via SEXP objects, and those require .Call(). So I suggest you read a
little more in "Writing R Extensions". As well as the Rcpp documentation.
And as you will learn in the "Rcpp-introduction" and other places, we use
what is called proxy model --- so yes, we do pass pointers and no, you don;t
get more lightweight than this.
Then again, R uses copy-on-write so if you want to truly alter without having
R create new copies for you then external pointers are your best bet.
Dirk
--
"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx
More information about the Rcpp-devel
mailing list