Daniel Schalk — written Dec 19, 2017 — source
When writing an
R package wrapping some
C++ data structures, using
is a convenient option. After exposing a class to
R, it can be used to
easily create new instances of that class.
As an example, let us look at the
Uniform class of the Rcpp Modules vignette:
After sourcing the file the
Uniform class can be used:
C++ object <0x55fd63177450> of class 'Uniform' <0x55fd63788a20>
What happens now, is that the uniform instance calls its default print method – which results in a fairly uninformative display. It would be nice if the printer of the instances could be customized to provide more information about the specific object.
It is possible to make use of the underlying
S4 structure of the exposed
 "Rcpp_Uniform" attr(,"package")  ".GlobalEnv"
Uniform class this is
Rcpp_Uniform. To obtain a custom printer the
last step now is to set the method
show and define the function which should
be used as printer:
Hi, I am an uniform object! I was initialized with a minimum value of 0 and a maximum value of 10. Therefore my range is 10.
This works very nicely. Now it is possible to provide some more informations about
Uniform instance. One thing to note is that
setMethod returns the
method name as string, which we assign to an otherwise unused variable.
To get that print method as a default printer after exposing the
C++ class to
within a package, it is sufficient to create a
R file (e.g.
R/uniform_printer.R) and put the following code in there: