[R] How can I pass a R matrix as parameter to C code?
Thomas Lumley
tlumley at u.washington.edu
Mon Mar 20 22:38:00 CET 2006
On Mon, 20 Mar 2006, johan Faux wrote:
> Hello,
>
> Is it possible to pass R matrix as a parameter to an internal C procedure?
> From the documentation I got the impression that only 1-dim vectors can be passed.
> Why the following wont work for me?
>
>
> > a<-matrix(1:15,3,5)
>> .C("pr",as.integer(a))
>
> void pr(int **a){
> a[1][1]=100;
> }
Because a is passed as int* rather than int**.
Matrices in R are stored as one-dimensional vectors with a "dim"
attribute. They can be passed to .C, but you have to pass the dim
information separately, eg
void pr(int *a, int *dim){
int nrow, ncol;
nrow=dim[0];
ncol=dim[1];
a[1] = 100; /* a[1,1] */
a[(10-1) + (5-1) * nrow] = 100; /* a[10,5] */
return;
}
called as
.C("pr",as.integer(a), as.integer(dim(a)))
In fact, int** wouldn't be the right type even for a C two-dimensional
array. The rule that array parameters decay to pointers is not applied
recursively, so int ** is the type for a one-dimensional vector of
pointers to int. If a variable has type int[3][5] it has to be passed as
*int[5] or int[][5] so that the compiler knows how far it is from a[1][1]
to a[2][1].
-thomas
More information about the R-help
mailing list