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

andre zege andre.zege at gmail.com
Fri Nov 4 04:53:21 CET 2011


Chris, i set a tiny matrix


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

cut your code  pasted it into R

after i run myfun(mm), i still have exactly the same matrix when i print mm
as before, not a doubled matrix

The function myfun did return a doubled matrix, but original matrix mm
stayed the same, so it still appears that original R memory was not changed
from C++

I maybe missing something very obvious, i don't understand how it's
possible that the same code seems to give you a different result, just
reporting what i personally observe when i go exactly through the motions
you suggested





On Wed, Nov 2, 2011 at 9:53 PM, Christian Gunning <xian at unm.edu> wrote:

> On Wed, Nov 2, 2011 at 4:00 AM,
> <rcpp-devel-request at r-forge.wu-wien.ac.at> wrote:
> >
> >
> > 1. in my previous post  i used exactly that same constructor you are
> > talking about as you can see from the code i posted
>
> Sorry about that, completely missed it...
> Using what's below, this should work fine.
>
> > 3. i am not 100% sure but this toy test that i did seem to indicate to me
> > that a copy is done regardless by NumericalMatrix. I need to see the code
> > for NumericMatrix to be absolutely sure, but i cannot explain things
> > otherwise
>
> 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
>
>
> --
> A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20111103/932f2220/attachment.htm>


More information about the Rcpp-devel mailing list