Define a custom print method for exposed C++ classes
This article is originally published at https://gallery.rcpp.org
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.
Customize the Printer
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.
Use in Packages
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:
Please visit source website for post related comments.