Writing Extensions in R
You can write extensions for R in FORTRAN or C to help speed things up. This is useful if your R code involves lots of loops or other things that can be better handled in an external language. Most of this information and more can be found in the
Writing R Extensions manual.
Hello world!
Let's start with the simplest extension in C: the obligatory "Hello world!" extension.
In your C source code, the first thing you have to do is include a few header files from the R library (in addition to any other includes you might need):
#include "R.h"
#include "Rdefines.h"
#include "R_ext/Rdynload.h"
The rest of the source includes any functions you want to call from R. In this example, we have a hello_world() function.
void hello_world() {
printf("Hello world!\n");
}
Easy enough. If you want to send arguments to any external functions (which you will probably want to do), you'll need to add some parameters with types specific to what you're expecting from the user. More on that with the next example.
Next you need to register this function with R and tell it how it should be called. You do this through the
R_init_<lib>
function, where
lib is the name of the shared library you want to create (in this case, "hello_world"). Here's the code needed for our example:
R_CMethodDef cMethods[] =
{
{"hello_world", (DL_FUNC)&hello_world, 0},
{NULL,NULL, 0}
};
void R_init_hello_world(DllInfo *dll)
{
R_registerRoutines(dll,cMethods,NULL,NULL,NULL);
}
Now you're ready to compile!