[R] how to call a C program from R function

Thomas Petzoldt thpe at hhbio.wasser.tu-dresden.de
Thu Aug 28 16:23:49 CEST 2003


Martin Olivier wrote:

> Hi all,
> 
> I would like to call a C program from R function. I tried to use the 
> .C() function
> without success. I need a very simple example (such as the hello 
> program) to understand

Do you want to call a C program (executable) or a shared library? If you 
want to run a compiled program simply use system() or shell()

> how it works. Could you give a  such example?
> (I use the  1.7.1 Version of R with linux)
> 
> Does it work in the case of a C++ program instead of a C programm?

If you want to call a shared library (or DLL), please look into the 
Manual "writing R extensions" and look for the "convolve example".

For a very simple "hello-function" see the "C++" example below. Please 
check if you have installed the correct compiler on Linux and look into 
the manual how to compile a shared library. On Linux it is:

R CMD SHLIB test.cpp


Thomas P.

-----------------------------------------------------------
A simple example, but there are better in the docs ;-) e.g. building a 
package.



===========================================================
// File test.cpp:

#include <R.h>
#include <Rinternals.h>

extern "C" {

void testarr(int* n, double* x) {
     for (int i = 0; i < *n; i++) {
        x[i] = 2 * i;
     }
   }
}
===========================================================
## file test.R

dyn.load("test.so")

testarr <- function(x) {
   .C("testarr", as.integer(length(x)), x=as.double(x))$x
}

print(testarr(1:10))

dyn.unload("test.so")




More information about the R-help mailing list