Skip to content

Instantly share code, notes, and snippets.

@jeffreyhanson
Created October 24, 2016 00:26
Show Gist options
  • Save jeffreyhanson/be6c6e9fa3ecabee4b86f82206d80e83 to your computer and use it in GitHub Desktop.
Save jeffreyhanson/be6c6e9fa3ecabee4b86f82206d80e83 to your computer and use it in GitHub Desktop.
This gist contains an example of using Rcpp::XPter in R
# load packages
library(Rcpp)
library(testthat)
# define functions
cppFunction('
Rcpp::List export_data(Rcpp::NumericVector x) {
std::vector<double> x1 = Rcpp::as< std::vector<double> >(x);
std::vector<double>* x2 = new std::vector<double>;
*x2 = x1;
Rcpp:XPtr< std::vector<double> > pointer(x2);
return(Rcpp::List::create(Rcpp::Named("ptr") = pointer));
}
')
cppFunction('
Rcpp::NumericVector import_data(Rcpp::List x) {
std::vector<double> x1 = *Rcpp::as< Rcpp::XPtr< std::vector<double> > >(x["ptr"]);
return (Rcpp::wrap(x1));
}
')
## main code
x = 1:10 # create initial R object
ptr = export_data(x) # sink R object to memory
x2 = import_data(ptr) # recover R object from memory
test_that('data has changed', expect_equal(x, x2)) # test that objects are the same
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment