[Rcpp-devel] Modify R object within C++ function that returns bool to indicate success/failure

Romain Francois romain at r-enthusiasts.com
Mon Jul 5 10:43:56 CEST 2010


Le 01/07/10 14:24, Paul Theodor Pyl a écrit :
>
> Hi all,
>
> I have a question concerning the modification of R objects within C++
> using Rcpp, what I would like to do is shown in this fantasy-R-session:
>  > l <- list()
>  > while( mycppfunc( l ) ){ print("running!") }
> running!
> running!
> ...
>  > l
> $a
> [1] "Something"
> $b
> ...
>
> The corresponding c++ function would look like this:
>
> bool mycppfunc( List l ){
> some_struct x;
> if( some_other_function( x ) ){
> l[x.name] = x.some_member;
> return true;
> }else{
> return false;
> }
> }
>
> where some_other_function is a c++ function that takes the struct and
> modifies it returning a bool to indicate success/failure.

List::operator[] might move the memory around (if you add a new element 
of the list), so the underlying SEXP will change. We have no choice 
about this, this is dictated by the R API. You need to return the list 
to the R level.

Something like:

while( TRUE ){
	 print("running!")
	res <- mycppfunc( l )
	if( ! res$more ) break ;
	l <- res$l
}

And then internally return a list that contains both the actual result 
and whether it needs to continue.

Alternatively, you could manage the loop internally in C++

> Looking at the examples of Rcpp so far I have not found one where an R
> object is handed to a c++ function that modifies it and returns a bool
> to indicate success / failure.
>
> How would I go about this? Could that be done using SEXP's (since they
> are pointers I would suspect they can be modified 'in-place')

Adding an element to a list is achieved by essentially creating a new 
list and copy the content of the initial list.

pairlists don't have that problem but they are weird animals on the R side.

> Cheers,
> Paul
> _______________________________________________
> 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
>
>


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/98Uf7u : Rcpp 0.8.1
|- http://bit.ly/c6YnCi : graph gallery collage
`- http://bit.ly/bZ7ltC : inline 0.3.5



More information about the Rcpp-devel mailing list