[R] Rcpp Starter With Carry Class
ivo welch
ivo.welch at anderson.ucla.edu
Tue May 28 20:41:05 CEST 2013
I read Hadley's excellent Rcpp tutorial at
https://github.com/hadley/devtools/wiki/Rcpp. Alas, there is one part
that is missing---how do I maintain a memory region between calls?
Here is a stylized example of what I mean:
extern "C" {
#include <stdio.h>
#include <math.h>
}
#include <new>
class silly {
double *v; int k;
public:
silly(int i) { k= i; v= new double[k]; }
~silly() { delete [] v; }
void update( int x1 ) { for (int i=0; i<k; ++i) v[i]= v[i]+pow(x1,i); }
int show() { for (int i=0; i<k; ++i) printf("i[%d]=%lf\n", i, v[i]);
return k; }
};
// the C++ version of what we will want to do
int main() { silly s(5); s.update( 1 ); s.update( 2 ); s.show();
return 0; }
### intended Rcpp syntax; I know I could do this by using R
attributes from Rcpp,
### but I want to learn how to keep my storage in C++ and update in place.
demonstrate <- function() {
x <- silly(5)
x <- update(x, 1)
x <- update(x, 2)
show(x)
}
I presume as far as R is concerned, heap-allocated memory is outside
its domain, so my *v vector is fine. is there a "Pointer" type that I
could define and schlepp through various invokations in R?
I am thinking
RLeaveMeAlonePointer silly(int i) {
RLeaveMeAlonePointer out;
out.attr("class") = "silly";
return out;
}
and is R smart enough to call C++ ~silly() when the last reference to
x disappears?
and is the overhead of a C++ call low or high?
/iaw
----
Ivo Welch (ivo.welch at gmail.com)
More information about the R-help
mailing list