[Rcpp-devel] How to access fields and methods of a RefClass from C++?

Dirk Eddelbuettel edd at debian.org
Wed May 29 01:49:59 CEST 2013

On 28 May 2013 at 23:14, Anwar Ludin wrote:
| Hello,
| I have a Reference class defined in R that I am passing as a parameter 
| to a C++ class using Rcpp. I am trying to access the fields of the 
| Reference class from C++ and I'm not sure how to do this.

Well for starters your reference class object had no field price so that
makes extracting it hard...

But in essence:  a) reference classes are S4 objects, and as b) you can see
from str() and unclass(), they contain an environment you can access. So try
this modification of your code:


Instrument <-setRefClass(
   fields=list("id"="character", "description"="character")
Instrument$accessors(c("id", "description"))

instrument <- Instrument$new(id="AAPL", description="Apple")

cat("\n\nInstrument unclassed:\n")
cat("\n\nInstrument .xData env.:\n")
print(ls(instrument at .xData))

std::string getId(S4 obj) {
    // get the environment
    Environment e = obj.slot(".xData");
    // extract field
    std::string txt = as<std::string>(e["id"]);
    // return it
    return txt;

cat("\n\nId extracted from instrument:\n")

Hope this helps,  Dirk

Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com

More information about the Rcpp-devel mailing list