Next: Speed
Up: R, S, and Splus
Previous: Installing R libraries locally
- R
- create your C or C++ or Fortran code; you may need to include the
header #include "R.h"; if using C++, enclose
all your functions with
extern "C"{
... your function code ...
}
- to use Fortran code, I usually call the Fortran function from C or
C++; remember to declare the Fortran function, e.g.:
extern "C" void rkbesld_(double* x,double*
alpha,int* nb,int* ize,double* bk, in t* ncalc); // the function
would be named rkbesld in the fortran file
extern "C" void myfun(int *n,double *x,double*
out){
... function code ...
}
- from the UNIX/Linux command prompt
>R COMPILE rkbesld.f; R CMD SHLIB file.C rkbesld.o
- Or, if you're not calling a fortran function, just
>R CMD SHLIB file.C
- start R and load the .so file created by the previous step
>dyn.load("file.so")
- write and use a wrapper function to access the C/C++ function (see
below)
- Splus
- old UNIX 3.X version:
from UNIX: >Splus COMPILE file.c
in S: >dyn.load2("file.o")
- Linux version:
>Splus CHAPTER file.{c,f} # this creates a Makefile;
it's ok if you already have chapter created (I think)
>Splus make # You may need to change the libraries and
linking that are specified in the Makefile created in CHAPTER command
- write and use a wrapper function to access the C/C++ function (see
below)
- wrapper functions
- the R/S wrapper function deals with the overhead of communicating
with C and lets you call your function as if it is in native R/S code,
for example, if the function name in file.{c,f} is myfun,
create the following wrapper:
>myfun=function(n, x){
out <- NULL
.C("myfun",as.integer(n),as.double(x),as.double(out))[[3]]
# returns out (the third element of the list returned by .C)
}
make sure the C/C++/Fortran function has all args passed by reference
(i.e., as pointers) and returns void (or else just write a C/C++/Fortran
wrapper to do this)
Next: Speed
Up: R, S, and Splus
Previous: Installing R libraries locally
Chris Paciorek
2006-04-02