[Amore-commits] First steps using Rcpp

Manuel Castejón Limas manuel.castejon at gmail.com
Sat May 21 10:35:50 CEST 2011


Hi all,
I've just started using Rcpp. This is a brief example using the inline
package to show how to define a C++ class and use it in R.
The RCPP_MODULE section translates the C++ class to methods accesible from
R.

# Remember, this is an R file
# 

# Author: mcasl

############################################################################
###





require("inline")

require("Rcpp")



test_code <- '

class Con {

public:

Con (int f_, double w_) : from(f_), weight(w_) {}



int from;

double weight;



int getFrom ()   {return(from);};

double getWeight () {return(weight);};

void setFrom (int f)   {from = f;};

void setWeight (double w) {weight = w;};

};



RCPP_MODULE(AMORE_module) {

class_<Con>( "Con" )

.constructor<int, double> ()

.field( "from", &Con::from )

.field( "weight", &Con::weight )

.method( "getFrom", &Con::getFrom )

.method( "setFrom", &Con::setFrom )

.method( "getWeight", &Con::getWeight )

.method( "setWeight", &Con::setWeight )



;

};

'



fx <- cxxfunction( signature(), "" , include = test_code, plugin = "Rcpp" )

AMOREmod <- Module("AMORE_module", getDynLib(fx))

gCon <- AMOREmod$Con



# Loading required package: inline

# Loading required package: Rcpp





gCon 

# C++ class 'Con' <0x10046e500>

# Constructors:

#     Con(int, double)

# 

# Fields: 

#     int from

#     double weight

# 

# Methods: 

#      int getFrom()

#            

#      double getWeight()

#            

#      void setFrom(int)

#            

#      void setWeight(double)

#            





mycon <- gCon$new(as.integer(5), 4.3)

# 

mycon

# C++ object <0x100466b00> of class 'Con' <0x10046e500>





mycon$getFrom()

mycon$setFrom(2)

mycon$getFrom()



# [1] 5

# [1] 2




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/amore-commits/attachments/20110521/356cf107/attachment.htm>


More information about the Amore-commits mailing list