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

Darren Cook darren at dcook.org
Fri Nov 4 07:48:18 CET 2011


> mm<-matrix(1:10, nr=2),
> ...
> after i run myfun(mm), i still have exactly the same matrix when i print mm
> as before, not a doubled matrix

I think there was a missing line in Christian's sample, which was:
   myfun(mmint)

I.e. the point of his code was to show that a matrix of doubles gets
modified, a matrix of ints does not.
(This is nothing to do with Armadillo by the way; I could run his code
without the "require(RcppArmadillo)" line.)

If you change your above code to this
   mm<-matrix(1:10*1.0, nr=2)

it then gets modified.

Darren


>> This is a little tricky, I almost missed it myself (again).
>> From the Quickref:
>> "If R/C++ types match, use pointer to x."
>> Use a non-integer input to your function and see if that works.  Take
>> a look at this example:
>>
>> src <- '
>> Rcpp::NumericMatrix r_m(mem);
>> int nn = r_m.nrow() * r_m.ncol();
>> // int nn = r_m.size();
>> // above doesnt work with NumericMatrix, .size() is ambiguous??
>> for (int ii =0; ii < nn; ii++) {
>>    r_m[ii] = r_m[ii] + r_m[ii];
>> }
>> return r_m;
>> '
>>
>> require(inline)
>> require(RcppArmadillo)
>> myfun = cxxfunction(signature(mem='numeric'), src, plugin='Rcpp')
>>
>> ll <<- mm <<- matrix((1:10)/10, nrow=2)
>> llint <<- mmint <<- matrix(1:10, nrow=2)
>> myfun(mm)
>> ## should be false, since myfun modifies mm directly?
>> print(all.equal(mm, ll))
>> print(all.equal(mmint, llint))
>>
>> hth,
>> -Christian

-- 
Darren Cook, Software Researcher/Developer

http://dcook.org/work/ (About me and my work)
http://dcook.org/blogs.html (My blogs and articles)


More information about the Rcpp-devel mailing list