Le 04/01/12 15:33, Hadley Wickham a écrit :
Hi all,

Is it a bug to cause a segfault with Rcpp? Or are am I doing something
so dumb that an automatic check could never protect?  See minimal
reproducible example below.

Hadley

library(inline)
f<- cxxfunction(signature(x = "numeric", i = "numeric"), plugin = "Rcpp", '
   Rcpp::NumericVector x_(x);
   Rcpp::NumericVector i_(i);

   x_[(int) (i_[0]) - 1] = 1000;

   return(x_);
')
f(1:10, 1) # works
f(1:10, 1.5) # also works
f(1:10, NA) # segfaults

That is because of underlying C++ double arithmetics:

fx <- cxxfunction( signature( x_ = "numeric"), '

    double x = as<double>(x_) ;
    Rprintf( "%5.2f\\n", x ) ;


', plugin = "Rcpp" )
fx( NA )

So your i_[0] - 1 is also nan. You are responsible for dealing with na.

You can use traits::is_na:

fx <- cxxfunction( signature( x_ = "numeric"), '

    double x = as<double>(x_) ;

    if( traits::is_na<REALSXP>(x) ){
        // do something
    } else {
        // do something else
    }

', plugin = "Rcpp" )

or perhaps if you don't like the whole traits::is_na<REALSXP> thing, you could use e.g. somethin like this:

template <typename T>
bool isna( T x ){
    return traits::is_na<traits::r_sexptype_traits<T>::rtype > (x) ;
}

so that you coud just call

if( isna(x) ){ ... }

Romain


--
Romain Francois
Professional R Enthusiast
http://romainfrancois.blog.free.fr

_______________________________________________
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Reply via email to