Skip to content
Prev 2726 / 10988 Next

[Rcpp-devel] integer arrays as arguments for a module function

On 12 August 2011 at 14:50, Chris DuBois wrote:
| Hi all,
| 
| I'm trying to figure out how to pass in an array of integers to a function
| inside a module. ?For example, adding the following function to runit.Module.R
| works fine:
| 
| ? ? ? ? int bla3( IntegerVector x ) {
| ? ? ? ? ? ? ? return sum(x);
| ? ? ? ? }
| 
| However, I need to pass an int array, rather than an IntegerVector. ?Using int
| x[] in the arguments doesn't compile (though I'm unfamiliar with C++ in
| general, so maybe this shouldn't work anyway). ?
| 
| Alternatively, should I just cast x from an IntegerVector to an int array? ?I
| tried various permutations of as, vector, <int>, etc, and would like to learn
| the proper way of doing this.

You generally do not want old school x[] arrays in C++. Why?  Because STL
vectors do _everything_ they do at (essentially) zero added cost, free you
from malloc/free and still allow you to access the straight memory should you
need to (to talk to a C API, say).

So use IntegerVector for _the interface_. You can the, if you must, do

     IntegerVector x;
     
     int a1[] = x.begin();     // STL-style iterator to beginning of memory
     int *a2  = x.begin();     // idem

Hope this helps,  Dirk