setRcppClass {Rcpp}R Documentation

Define a Reference Class containing a C++ Class

Description

Function setRcppClass creates an extended reference class that contains an interface to a C++ class, typically as exposed by an Rcpp Module. The Rcpp class can have R-based fields and methods in addition to those from the C++ class.

Usage

setRcppClass(Class, CppClass = , fields = list(), contains = character(), methods = list(), where = topenv(parent.frame()), ...)

Arguments

Class

The name of the class to be defined.

CppClass

The C++ class extended by this class, usually a class specified in an Rcpp Module.

fields, contains, methods, where, ...

Arguments to setRefClass, extended in the case of contains= to include the C++ class.

Value

A generator object for the reference class. The generator object is from class "rcppObjectGenerator", with some extra slots to hold information about the contained C++ class.

Author(s)

John Chambers

Examples

## Not run: 
### Following the vignette for Module exporting C++ class Uniform
### The class randU extends the C++ class to maintain seed for the RNG
### (An example of a reproducible simulation utility, protected
### from any other random number generation.  Class "Rseed", not shown,
###  mainly exists to print random seeds in a user-readable form.)
randU <- setRcppClass("randU", Uniform,
    fields = list(startSeed = "Rseed", currentSeed = "Rseed"),
    methods = list(
    set.seed = function(seed) {
        base::set.seed(seed)
        startSeed <<- as(.Random.seed, "Rseed")
        currentSeed <<- startSeed
        invisible(currentSeed)
    },
    draw = function(...) {
        if(exists(".Random.seed",envir = .GlobalEnv)) {
            previous <- get(".Random.seed", envir= .GlobalEnv)
            on.exit(assign(".Random.seed", previous, envir = .GlobalEnv))
        }
        else
            on.exit(remove(".Random.seed", envir = .GlobalEnv))
        assign(".Random.seed", currentSeed, envir = .GlobalEnv)
        value <- callSuper(...)
        currentSeed <<- as(get(".Random.seed", envir = .GlobalEnv),
                           "Rseed")
        value
    }
    )
)
randU$lock("startSeed")

## End(Not run)
## Not run: 

## This class can be used with mixed R/C++ methods:

ru <- randU$new(0,10)
ru$set.seed(429)
ru$draw(10)

## End(Not run)

[Package Rcpp version 0.9.10 Index]