|
Rcpp Version 0.9.10
|
00001 #!/usr/bin/r -t 00002 # 00003 # Copyright (C) 2009 - 2010 Romain Francois 00004 # 00005 # This file is part of Rcpp. 00006 # 00007 # Rcpp is free software: you can redistribute it and/or modify it 00008 # under the terms of the GNU General Public License as published by 00009 # the Free Software Foundation, either version 2 of the License, or 00010 # (at your option) any later version. 00011 # 00012 # Rcpp is distributed in the hope that it will be useful, but 00013 # WITHOUT ANY WARRANTY; without even the implied warranty of 00014 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 # GNU General Public License for more details. 00016 # 00017 # You should have received a copy of the GNU General Public License 00018 # along with Rcpp. If not, see <http://www.gnu.org/licenses/>. 00019 00020 require(Rcpp) 00021 require(inline) 00022 00023 funx <- cxxfunction(signature(), ' 00024 /* creating a pointer to a vector<int> */ 00025 std::vector<int>* v = new std::vector<int> ; 00026 v->push_back( 1 ) ; 00027 v->push_back( 2 ) ; 00028 00029 /* wrap the pointer as an external pointer */ 00030 /* this automatically protected the external pointer from R garbage 00031 collection until p goes out of scope. */ 00032 Rcpp::XPtr< std::vector<int> > p(v) ; 00033 00034 /* return it back to R, since p goes out of scope after the return 00035 the external pointer is no more protected by p, but it gets 00036 protected by being on the R side */ 00037 return( p ) ; 00038 ', plugin = "Rcpp" ) 00039 xp <- funx() 00040 stopifnot( identical( typeof( xp ), "externalptr" ) ) 00041 00042 # passing the pointer back to C++ 00043 funx <- cxxfunction(signature(x = "externalptr" ), ' 00044 /* wrapping x as smart external pointer */ 00045 /* The SEXP based constructor does not protect the SEXP from 00046 garbage collection automatically, it is already protected 00047 because it comes from the R side, however if you want to keep 00048 the Rcpp::XPtr object on the C(++) side 00049 and return something else to R, you need to protect the external 00050 pointer, by using the protect member function */ 00051 Rcpp::XPtr< std::vector<int> > p(x) ; 00052 00053 /* just return the front of the vector as a SEXP */ 00054 return( Rcpp::wrap( p->front() ) ) ; 00055 ', plugin = "Rcpp" ) 00056 front <- funx(xp) 00057 stopifnot( identical( front, 1L ) ) 00058