Let’s start this with some disclosure: I have recently grown to love R (despite it’ drawbacks), and I first ‘learned’ C about 10 years ago in an undergraduate class (wow, that’s weird to think about). Apparently, though, I was staring at girls more than my textbook or the PuTTY terminal, and now I’m paying for it. But who could blame me? I was a mechanical engineer, fresh out of high school, and I thought a computer existed primarily for using Napster and Microshit Word. (And Napster was free, cool, and awesome.) So now, as a graduate student, I realize I should have cared about that class on C.
Yes, FORTRAN is still extensively used in the geosciences, but reading it is about as enjoyable as looking at a troff document. Fortunately Stack Overflow (SO) exists, and is well ranked in most Google queries, so I can quickly refresh my C skills. It’s unfortunate that public forums often engender snarky responses, especially to half-baked questions, but SO has managed to keep that effect to a minimum; I think it’s mostly due to the ingenious point-awarding system used by them.
OK, why am I writing all this? I recently decided that using METEOR, a FIR filter-design code, would be fruitful. It compiles fine with gcc and there’s an example to test it’s usage, but that’s not good enough these days: I want to access it directly inside R. There is a function in the twenty-something year old code that uses STDIO’s getchar(), but that poses an input problem to a naive user (me). So, I don’t know if there’s a solution besides this…
Let’s say I have a C-code rdarr.c:
#include <stdio.h>
#include <stdlib.h>
int rdarr(char *myarr[], int narr[])
{
int n = narr[0];
int i;
printf(">>>> %i\n",n);
if (n < 1E4) {
for(i = 0; i < n; i++){
printf("\t%s\n", myarr[i]);
}
}
printf("<<<<\n");
return (EXIT_SUCCESS); /* stdlib */
}
which is compiled using R CMD SHLIB rdarr.c.
If there is a function in R which accesses that C-code, like this:
dyn.load("rdarr.so")
rdarrC <- function(arr, narr){
unlist(.C("rdarr", arr, narr))
}
we can say, for example, rdarrC(c("a","b"), 2) and get:
>>>> 2
a
b
<<<<
So the trick will be to use something like this as a string-block reader. But, because R apparently uses arrays for any inputs to .C(), this only works when the zero-index value of the array is referenced (thus the int n = narr[0]; statement in the C-code).
It is a bit annoying to me, but I don’t know another way to do it, and the same situation might be a major gotcha-type issue for others. While I do still consider myself new to all this, there are many exciting directions integrating C with R can go.
Suggestions for improvement welcomed; but, cheers – to the learning curve!

