Created
February 4, 2020 21:29
-
-
Save hpwxf/306b04f07b7b6c5da2f10a956dbfa58c to your computer and use it in GitHub Desktop.
Object binding between C++ and R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// About C++11: https://teuder.github.io/rcpp4everyone_en/050_c++11.html | |
// [[Rcpp::plugins("cpp11")]] | |
/* R demo | |
* | |
* library(Rcpp) | |
* sourceCpp("test.cpp") | |
*/ | |
#include <Rcpp.h> | |
//// using raw pointer | |
struct Kr { | |
int i; | |
std::string s; | |
}; | |
// [[Rcpp::export]] | |
SEXP build() { | |
Kr *a = new Kr{42,"42"}; | |
Rcpp::XPtr<Kr> ptr(a); // TODO: check memory management | |
return ptr; | |
} | |
// [[Rcpp::export]] | |
int apply(SEXP a){ | |
Rcpp::XPtr<Kr> x(a); | |
int i = x->i; | |
return i; | |
} | |
/* R demo | |
* | |
* a <- build() | |
* apply(a) | |
*/ | |
/// Using S3 | |
/* R demo | |
* | |
* a <- structure(list(x=42), class = "kr") | |
* OR | |
* a <- buildS3() | |
* class(a) | |
* inherits(a, "kr") | |
* applyS3(a) | |
*/ | |
//Receiving kr() model object and calculate RMSE | |
// [[Rcpp::export]] | |
Rcpp::List buildS3() { | |
Rcpp::List obj; | |
obj.attr("x") = 42; | |
obj.attr("class") = "kr"; | |
return obj; | |
} | |
// [[Rcpp::export]] | |
int applyS3(Rcpp::List obj) { | |
if (! obj.inherits("kr")) Rcpp::stop("Input must be a km object"); | |
return obj.attr("x"); | |
} | |
/// Using S4 | |
// [[Rcpp::export]] | |
SEXP buildS4() { | |
Rcpp::S4 obj("kr"); | |
obj.slot("x") = 1000; | |
return obj; | |
} | |
// [[Rcpp::export]] | |
std::string applyS4(Rcpp::S4 obj) { | |
return obj.slot("y"); | |
} | |
/* R demo | |
* | |
* setClass("kr", representation(x="numeric", y="character"), prototype = list(x=42, y="42")) | |
* a <- buildS4() | |
* applyS4(a) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment