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

Dirk Eddelbuettel edd at debian.org
Thu May 30 16:02:27 CEST 2013


On 30 May 2013 at 15:15, Romain Francois wrote:
| More easily, you can use Rcpp::Reference:
| 
| // [[Rcpp::export]]
| std::string getId(Reference obj) {
|      std::string txt = obj.field("id");
|      return txt;
| }

Thanks -- had forgotten about that one.  

Would you mind cooking up a quick unit test for this as a reminder?

Dirk
 
| Here, you are isolated from the implementation of reference classes 
| using environments and the .xData slot name.
| 
| Romain
| 
| Le 29/05/13 01:49, Dirk Eddelbuettel a écrit :
| >
| > 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:
| >
| >
| > library(Rcpp)
| > library(methods)
| >
| > Instrument <-setRefClass(
| >     Class="Instrument",
| >     fields=list("id"="character", "description"="character")
| > )
| > Instrument$accessors(c("id", "description"))
| >
| > instrument <- Instrument$new(id="AAPL", description="Apple")
| >
| > cat("Instrument:\n")
| > print(instrument)
| > #print(str(instrument))
| > cat("\n\nInstrument unclassed:\n")
| > print(unclass(instrument))
| > cat("\n\nInstrument .xData env.:\n")
| > print(ls(instrument at .xData))
| >
| > cppFunction('
| > 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")
| > print(getId(instrument))
| >
| >
| >
| > Hope this helps,  Dirk
| >
| 
| 
| -- 
| Romain Francois
| Professional R Enthusiast
| +33(0) 6 28 91 30 30
| 
| R Graph Gallery: http://gallery.r-enthusiasts.com
| 
| blog:            http://blog.r-enthusiasts.com
| |- http://bit.ly/Zs97qg  : highlight 0.4.1
| `- http://bit.ly/10X94UM : Mobile version of the graph gallery
| 
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

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


More information about the Rcpp-devel mailing list