Skip to content

[Rcpp-devel] Problem passing Armadillo objects back to R

5 messages · Davor Cubranic, Romain Francois, "Günter J. Hitsch"

#
Good news. I can reproduce it.
Bas news. This is likely a PROTECT problem with the Rcpp::List constructor.

Wearing my bugbuster costume, and getting ready for a fight.

Romain

Le 07/03/11 23:03, "G?nter J. Hitsch" a ?crit :

  
    
#
Hmmmmmmmm. I'm afraid I can't fix this.

Here is the story: both wrap(X) and wrap(X) create a new SEXP and 
allocate memory. When wrap(Y) is called, since the created object is 
large, R calls the GC to collect unprotected SEXP to free some space. So 
my guess is that at that point the SEXP that is generated by wrap(X) is 
collected since it is not protected.

I can not deal with this inside ::create, because it is too late.


A Workaround is to use this :

return Rcpp::List::create(
Rcpp::Named("X") = X,
Rcpp::Named("Y") = Y
);

i.e. use the implicit wrap. here wrap will be called much later and 
things are fine.


The issue is that when calling wrap it creates an unprotected SEXP, and 
Rcpp is not responsible for these. If the programmer passes an 
unprotected SEXP to ::create, it is his responsability to protect it. So 
another alternative would be:

SEXP xx = PROTECT( wrap( X ) ) ;
SEXP yy = PROTECT( wrap( Y ) ) ;
Rcpp::List result =  Rcpp::List::create(
Rcpp::Named("X") = xx,
Rcpp::Named("Y") = yy
);
UNPROTECT(2) ;
return res ;

yes, this is ugly.

Romain

Le 06/04/11 11:42, Romain Francois a ?crit :

  
    
#
To make it harder for users to shoot themselves in the foot with 'List::create(Named("x") = wrap(X), ...', is it possible to make it simply illegal to assign an explicit "wrap" to a "Named"? This would force everyone to use implicit wraps, which as you said are safe.

Davor
On 2011-04-06, at 4:22 AM, Romain Francois wrote:

            
#
Le 06/04/11 17:12, Davor Cubranic a ?crit :
Not sure. This would I guess require that create don't take SEXP as 
arguments. This would break more things than it solves.

I fought this during several hours this morning until I realized "well I 
just can't do anything", but at least now I'll be quicker to identify 
similar things.

BTW, the problem also exists with unnamed components in create:

return Rcpp::List::create(
   Rcpp::wrap(X),
   Rcpp::wrap(Y)
);

This exhibits the same problem.

Romain

  
    
#
Thank you, Romain.  Looks like your simple workaround fixes all my problems.

G?nter
On Apr 6, 2011, at 6:22 AM, Romain Francois wrote: