[Rcpp-devel] Simplest Class Example For Starters

ivo welch ivo.welch at gmail.com
Thu May 30 18:42:32 CEST 2013


dear readers:  I am trying to learn how to interface a simple C++ class
into the underbelly of R.   I don't plan to use this regularly---just for
one or two applications.  I read the introduction and faq vignettes and
hadley's tutorial.   alas, I am mixing and matching badly.  I also don't
have the full template programming background, which dates me, and the
examples are quickly going down roads that are not illustrative of where I
want to go.

I would like to get a deliberately simple working example of a plain C++
class.  if no good example exists, here is one I made up that should be
fairly canonical.  the R code should be something like

library(Rcpp)
sourceCpp("silly.cpp")
test <- function() {
  silly.object <- Silly(100)  ## initializer
  silly.object <- update( silly.object, 10 )  ## updater
  show( silly.object )  ## results
  silly.object <- update( silly.object, 20 )
  show( silly.object )
  ## don't leak but call destroy on the silly example
}
test()


the C++ code in silly.cpp should wrap/glue the following:

struct Silly {
    double *v; int k;  // shows internal memory allocation
public:
    Silly(int i) { k=i; v=new double[k]; }
    ~Silly() { delete [] v; }
    void update( double x1 ) { for (int i=0; i<k; ++i) v[i]= v[i]+x1*i; }
    int show() { for (int i=0; i<k; ++i) printf("i[%d]=%lf\n", i, v[i]);
return k; }
}


that's it.  here, I know all the types.  I think I don't need SEXPs (or
maybe I do?), because I know I want to deal with numerics.  silly.object is
my class object (or pointer to one Silly struct) that I want to carry along
in R, but not have R know more about.  the argument to update() is known to
be a double (or we could make it a NumericVector) for simplicity sake.

if this sort of example is easier done with C and structs instead of C++
and classes, I would be ok with this, too.  If the example were embedded in
a cppFunction() call, even better.  I prefer as little ceremony (glue) as
possible/necessary.

could someone please point me to a standalone example that is similar?
 once I have this, experimenting should become a whole lot easier.  (PS:
This might make a nice opening of a tutorial, or a nice piece for the R
tutorial.)

advice appreciated.

/iaw
----
Ivo Welch (ivo.welch at gmail.com)
----

----
Ivo Welch (ivo.welch at gmail.com)
http://www.ivo-welch.info/
J. Fred Weston Professor of Finance
Anderson School at UCLA, C519
Director, UCLA Anderson Fink Center for Finance and Investments
Free Finance Textbook, http://book.ivo-welch.info/
Editor, Critical Finance Review, http://www.critical-finance-review.org/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130530/d024245a/attachment-0001.html>


More information about the Rcpp-devel mailing list