简体   繁体   中英

Passing R matrix to a low-level .C function, accessing the array to change its values

I'm exploring the basic .C call -- for a C standard experience -- passing a R matrix to a C function, using it as a (bi-dims) C array. Working on (1-dim) vectors I don't have any problem, but in this case I receive a core dump. How can I access every single cell of my array and change its values? Is it the right approach?

My R matrix:

> x <- matrix((1:100), ncol=10, nrow=10)
> x
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1   11   21   31   41   51   61   71   81    91
 [2,]    2   12   22   32   42   52   62   72   82    92
 [3,]    3   13   23   33   43   53   63   73   83    93
 [4,]    4   14   24   34   44   54   64   74   84    94
 [5,]    5   15   25   35   45   55   65   75   85    95
 [6,]    6   16   26   36   46   56   66   76   86    96
 [7,]    7   17   27   37   47   57   67   77   87    97
 [8,]    8   18   28   38   48   58   68   78   88    98
 [9,]    9   19   29   39   49   59   69   79   89    99
[10,]   10   20   30   40   50   60   70   80   90   100

This is the R function:

testr <- function(x) {
  d <- as.integer(dim(x))
  r <- .C("testc",
        d,
        x <- as.integer(x))
  return(r[[2]])
}

And this is the relative C function:

#include <stdio.h>
#include <math.h>

void testc(int *dim, int *x) {
  int i, j;

  for (j = 0; j < dim[0]; j++) {
    for (i = 0; i < dim[1]; i++) {
      x[j][i] = pow(x[j][i], 2);
    }
  }
}

The comment by Alexis Laz is spot on: the .C() interfaces forces the conversion of what in R is a matrix (in essence: a vector plus dimension attributes) down to just the vector without dimension.

That is one of many reasons why the recommendation these days is to use .Call() with its richer interface using SEXP objects. And if you use Rcpp you don't even have to anything:

R> cppFunction("NumericMatrix doubleMe(NumericMatrix M) { return 2*M; }")
R> doubleMe(matrix(1:9, 3))
     [,1] [,2] [,3]
[1,]    2    8   14
[2,]    4   10   16
[3,]    6   12   18
R> 

This just defined an Rcpp one-liner to take a matrix and return twice its value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM