[R] how to call R function from my C++ program

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun May 4 09:27:22 CEST 2003


I am inferring that you are using Linux, although you didn't say. Some of 
my answers are specific to Unix/Linux.

On Sat, 3 May 2003, Yan Yu wrote:

> I read the manual, it seems that i have the following two choices:
> 1) use "eval(R_fcall, rho)" in a C function.
> 
> They use an example called lapply2
> 
> in C program, it has:
> SEXP  lapply2(SEXP list, SEXP fn, SEXP rho)
> {
> .....
> PROTECT( R_fcall = lang2(fn, R_nilValue) );
> eval(R_fcall, rho)
> ......
> }
> 
> but i am a little confused here, it seems like the C function "lapply2()"
> is supposed to be called from R, not to be run standalone??
> My Q is: if I use this approach, Can I run a standalone C program in which
> I call a R function using eval()?

Yes.  You can build R as a shared library (libR.so) and link against that.
However, you will need to initialize R: see the examples in the directory
tests/Embedding in the sources, and the background URL

http://developer.r-project.org/embedded.html


> 2) R have some API entry points for C code.
> in section 5.12, it says "it is possible to build Mathlib, can be built in
> directory "src/namth/standalone", and the instructions are supposed in
> "README" in the same directory.
> I am wondering using the same procedure, can I build API entry points for
> other R functions I want to use?

No.  (Those are not for R functions, but for parts of R's C API, and 
considerable work was done to separate out that part of the API to make 
it work standalone.)

> I have another Q, there is no "src" subdirectory in my R directory.
> i use i386 rpm to install R in my redhat..
> i think the version i have now is R-1.6.1-1.i386.rpm..
> Any idea where can i find this src subdirectory?

In the sources.  You installed a binary version of R.  I suspect you will 
need to build from the sources to build libR.so.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list