I’ve written up a function “foo” in C that I want to call from an R program. The function takes in as input a matrix and does some operations on it, (say add 1 to each element). While it is easy to a single vector as
.C("foo", n=as.integer(5), x=as.double(rnorm(5)))
with foo implemented as
void foo(int *nin, double *x)
{
int n = nin[0];
int i;
for (i=0; i<n; i++)
x[i] = x[i] * x[i];
}
How do I pass in a two dimensional array? If I change the “double *x” to “double **x” it gives a segmentation fault. Any pointers appreciated.
No need to give up on
.Cfor straight-forward manipulations like this. Remember that a matrix in R is a vector + dimensions. Likewise in C, so pass the matrix and its dimensions, and access elements of the matrix as appropriate offsets into a vector. Something likeso using
inlineas a nice party trick