[Rcpp-devel] Underflow of unsigned integers

Dirk Eddelbuettel edd at debian.org
Wed Mar 5 12:47:06 CET 2014


On 5 March 2014 at 12:07, Xavier Robin wrote:
| Given the following function:
| > // [[Rcpp::export]]
| > void test_size_t(size_t s) {
| >     std::cout << s << std::endl;
| > }
| compiled with sourceCpp or in a package, I get the following behavior:
| > > test_size_t(-1)
| > 18446744073709551615
| Of course this is not what I want. I would be OK with the value being 
| set to 0, or preferably an error being thrown for instance...
| 
| Therefore I tried to defined a custom as<size_t>() as explained in 
| [http://gallery.rcpp.org/articles/custom-as-and-wrap-example/]. In a 
| convert.h file I defined:
| > #include <RcppCommon.h>
| > namespace Rcpp {
| >     // size_t
| >     template <> size_t as(SEXP ptr);
| >     ...
| > }
| And in the corresponding convert.cpp:
| > #include "boost/numeric/conversion/cast.hpp"
| > #include <Rcpp.h>
| > namespace Rcpp {
| >     // size_t
| >     template <> size_t as(SEXP ptr) {
| >         long long i(as<long long>(ptr));
| >         return boost::numeric_cast<size_t>(i);
| >     }
| >     ...
| > }
| Unfortunately my custom as<size_t>() is apparently not executed. I still 
| get overflows despite the fact I included the convert.h in the cpp file 
| I source, and when printing some output in as() nothing is printed out.
| 
| Of course I could define my function as void test_size_t(int i) and do 
| the conversion there, but I'd prefer some more fool-proof solution.
| 
| Any ideas?

R only knows (signed) integer and double so mapping from all C/C++ types is
always a challenge.

In your convert.cpp you may also get issue s with long long int which is not
supported everywhere; this will get better in six weeks when you can simply
turn on support for C++11 via a single toggle:

    edd at max:~/git$ tail -3  rcppcnpy/src/Makevars

    USE_CXX1X = 

    edd at max:~/git$ 

(which eg the RcppCNPy package shown here needs for the same reason of long
long int support).

Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list